Sharing Data in Struct

PressRex profile image
by PressRex
Sharing Data in Struct

Dear community,

I have a struct as follows:

struct Person {
    name: String
    age: u32
}

Given a mutable instance of Person, how can I create another immutable instance whose name data is shared with the first one? Example:

// When orig goes out of scope/dropped/etc.,
// an error should be raised if copy is accessed
// OR a copy/clone of the name field be made.
let mut orig = Person{ name: String::from("Adam"), age: 32 }
let copy = Person{ name: orig.name, age: 64} // What to do?
orig.name = String::from("Alice");

assert_eq!(String::from("Alice"), copy.name);

I'm new to Rust and not very familiar with its ownership rules. My only option seems to be RefCell?

5 posts - 3 participants

Read full topic

Source: View source

PressRex profile image
by PressRex

Subscribe to New Posts

Lorem ultrices malesuada sapien amet pulvinar quis. Feugiat etiam ullamcorper pharetra vitae nibh enim vel.

Success! Now Check Your Email

To complete Subscribe, click the confirmation link in your inbox. If it doesn’t arrive within 3 minutes, check your spam folder.

Ok, Thanks

Read More