Question

I have the following code (as a cut-down example):

class Item {
   attributes: ~mut [~str];
}

class ItemList {
   items: ~mut [ ~Item ];
}

fn read_item(rdr : Reader) -> ~mut Item {
}

fn load_item_list(rdr : Reader) -> ~mut ItemList {
}

When trying to implement these functions, I keep running into errors like "unresolved name ItemList" and conflicts between pointer/mutability types (&~mut vs ~mut, etc.)

Could someone give me a cut-down example which just allocates and returns the empty objects? From there I should be able to fill in the data.

Was it helpful?

Solution

I'm not sure what problem you are hitting but here are a few pointers. First of all, I recommend moving to Rust trunk - the class syntax you are using indicates a fairly old version of Rust. On trunk, mut is no longer a valid modifier for the interior of owned types, meaning ~mut T cannot be written, nor struct { mut field: T }. Instead mutability of owned types is inherited through its root in the stack. So if you have type Foo = ~[~str], that type is deeply immutable when declared in let foo = ~[~"bar"] and deeply mutable when let mut foo = ~[~"bar"].

Here's an example based on your types.

struct Item {
    attributes: ~[~str]
}

struct ItemList {
    items: ~[ ~Item ]
}

fn read_item() -> ~Item {
    ~Item {
        attributes: ~[~"puppies"]
    }
}

fn load_item_list() -> ~ItemList {
    ~ItemList {
        items: ~[read_item()]
    }
}

fn main() {
    let mut my_items = load_item_list();

    my_items.items[0].attributes[0] = ~"kitties";
}

You can see that the types don't mention mutability at all, but because we load them into a mutable slot (let mut my_items), the values in the inner vector can be mutated.

This can take some time to get used to, but Rust deals with interior mutability this way to avoid some potentially confounding errors related to borrowed pointers.

The exception to this inherited mutability is with managed types, which can also be the root of mutability, as in @mut T.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top