Hello,
I have some questions on how to do a few things in D.
Below is an example code on which the questions are based.

I need read access to a big and complex (i.e.: nested) data
structure of type "Node".
But first it needs to be initialized. That can be done with a
default initializer or from a file.
After initialization there is no need to modify the data anymore.
My first question is: can the data be changed to "const" once
initialized?
if no, is there any alternative to acomplish that?
note that encapsulating into a class with only "get_*" methods
does not help because the "get_node" method returns a pointer to
the data
Related to that, how can the default initializer be changed to
immutable?

The second question is related to pointers, references and values
I know that structs by default use value semantics, but as data
is large I want to avoid data copying.
But I would like to avoid use of pointers, so, is there a way of
using reference semantics in the example code?
Maybe is as simple as changing from "struct Node" to "class
Node", but seems intuitive that classes carry more overhead than
structs.
How much overhead carries a class in comparison to a struct?

Regards,
   Vicente.


import std.stdio;
import std.string;

// struct or class
struct Node {
        Node[] block;
        uint num = 0;
};

// static immutable
Node[] default_nodes = [
        {num:3},
        {block:[{num:4},{num:6},{block:[{num:5},{num:7}]}]},
        // ...
];

class NodeProvider{
        // change to const after constructor
        private Node[] nodes;

        private void parse_file(char[] file_name){
                // initialize nodes from file
                for(auto i=0; i<3; i++){
                        nodes.length++;
                        nodes[$-1].num=i;
                }
        }

        this(){
                nodes = default_nodes;
        }
        this(char[] file_name){
                parse_file(file_name);
        }

        Node* get_node(const uint index){
                if(index>=nodes.length)
                        return null;
                return &(nodes[index]);
        }
}

string NodetoString(Node n){
        string str = format("%u{ ", n.num);
        foreach(b;n.block)
                str ~= NodetoString(b);
        str ~= "} ";
        return str;
}

int main(char[][] args){
        NodeProvider np;
        Node* node_ptr;
        uint i;

        if(args.length==2)
                np = new NodeProvider(args[1]);
        else
                np = new NodeProvider();

        i = 0;
        while((node_ptr=np.get_node(i))!=null){
                writeln(NodetoString(*node_ptr));
                i++;
        }
        return 0;
}

Reply via email to