DEV Community

Cover image for Learning Rust: Structuring Data with Structs

Learning Rust: Structuring Data with Structs

Andrew Bone on March 18, 2024

Another week, another dive into Rust. This time, we're delving into structs. Structs bear resemblance to interfaces in TypeScript, enabling the gro...
Collapse
 
programcrafter profile image
ProgramCrafter

Ownership can be transferred between struct instances by either updating a field from one instance to match that of another instance or by utilising the .. syntax to move selected parts of the instance over.

It's worth noting that this (tracking which fields are moved out) causes a great deal of complications to Rust core team so this functionality is possibly subject to change.

Collapse
 
link2twenty profile image
Andrew Bone

I didn't know that, is much of the Rust language still subject to change?

Collapse
 
programcrafter profile image
ProgramCrafter

Quite so! You may look at list of tracking issues, or, for a central example, into Rustonomicon:

<...> Of course, we should probably define what aliased means. <...>

Unfortunately, Rust hasn't actually defined its aliasing model. πŸ™€

While we wait for the Rust devs to specify the semantics of their language, let's use the next section to discuss what aliasing is in general, and why it matters.

Collapse
 
adesoji1 profile image
Adesoji1

Everything you have written is correct

Collapse
 
link2twenty profile image
Andrew Bone

Well that is a relief ☺️

Collapse
 
kapaseker profile image
PangoSea

Issue:
// At this point, book1.rating and book1.unix_release_date
// have been moved to book2 and are no longer accessible

not really true, the f32 implemented Copy trait, so they are not moved to book2, just copy, you can still access book1.rating and book1.unix_release_date.

struct Book {
  title: String,
  rating: f32,
}


fn main() {
    let apple = Book {
        title:String::from("Apple"),
        rating:9.0f32,
    };

    let google = Book {
        title:String::from("Google"),
        ..apple
    };

    println!("apple rating: {}, google rating: {} ", apple.rating, google.rating);
}
Enter fullscreen mode Exit fullscreen mode