Matrix
Matrix

Reputation: 152

How does Rust's struct hold and use a object?

I need to use a struct to hold a serde_json object, and use it later.

extern crate serde_json;

use serde_json::builder::ObjectBuilder;

struct MyStruct {
    builder: ObjectBuilder,
}

impl MyStruct {
    fn new() -> MyStruct {
        MyStruct { builder: ObjectBuilder::new() }
    }

    fn add_string_member(&self, name: &str,  value: &str) {
        self.builder.insert(name, value); //here compile error
    }
}

fn main() {
    let s = MyStruct::new();
    s.add_string_member("name", "value");
}

But I get the error

error: cannot move out of borrowed content [E0507]

Upvotes: 0

Views: 134

Answers (1)

Francis Gagné
Francis Gagné

Reputation: 65822

The methods in ObjectBuilder take self by value. Since you can't move something out of a borrowed pointer, the easy solution is to make your methods on MyStruct take self by value as well.

Also, ObjectBuilder's methods return a new ObjectBuilder with the changes. You can wrap that return value into a new MyStruct, which you can return from your methods.

extern crate serde_json;

use serde_json::builder::ObjectBuilder;

struct MyStruct {
    builder: ObjectBuilder,
}

impl MyStruct {
    fn new() -> MyStruct {
        MyStruct { builder: ObjectBuilder::new() }
    }

    fn add_string_member(self, name: &str, value: &str) -> MyStruct {
        MyStruct { builder: self.builder.insert(name, value) }
    }
}

fn main() {
    let s = MyStruct::new();
    let s = s.add_string_member("name", "value");
}

If MyStruct also contains other members that you'd like to carry on into the new MyStruct, you can use a shortcut syntax to initialize the remaining fields of MyStruct from an existing instance:

fn add_string_member(self, name: &str, value: &str) -> MyStruct {
    MyStruct { builder: self.builder.insert(name, value), ..self }
}

Here, the builder field of the new MyStruct will be set to the specified expression, and all other fields will be moved from self. (The .. syntax accepts any expression of the proper type, not just self.)

Upvotes: 1

Related Questions