Struct update syntax ? [rustlings]

I have this :

fn create_order_template() -> Order {
    Order {
        name: String::from("Bob"),
        year: 2019,
        made_by_phone: false,
        made_by_mobile: false,
        made_by_email: true,
        item_number: 123,
        count: 0,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn your_order() {
        let order_template = create_order_template() {
            name: String::from("Hacker in Rust")
        }

but how can I update the name with the struct update syntax

maybe this is what you want:

let mut order_template = create_order_template();
order_template = Order {name: String::from("Hacker in Rust"), .. order_template};

this topic is in the rust book:

https://doc.rust-lang.org/book/ch05-01-defining-structs.html?highlight=update,syntax#creating-instances-from-other-instances-with-struct-update-syntax

Thanks,

The stupid test is still failing :

fn your_order() {

       let order_template = create_order_template(); 

       your_order = Order {

           name : String::from("Hacker in Rust"),

           .. order_template

       };

       assert_eq!(your_order.name, "Hacker in Rust");

! Compiling of exercises/structs/structs2.rs failed! Please try again. Here's the output:
error[E0308]: mismatched types
  --> exercises/structs/structs2.rs:36:22
   |
36 |           your_order = Order {
   |  ______________________^
37 | |             name : String::from("Hacker in Rust"),
38 | |             .. order_template
39 | |         };
   | |_________^ expected fn item, found struct `Order`
   |
   = note: expected fn item `fn() {tests::your_order}`
               found struct `Order`

error[E0070]: invalid left-hand side of assignment
  --> exercises/structs/structs2.rs:36:20
   |
36 |         your_order = Order {
   |         ---------- ^
   |         |
   |         cannot assign to this expression

error[E0609]: no field `name` on type `fn() {tests::your_order}`
  --> exercises/structs/structs2.rs:40:31
   |
40 |         assert_eq!(your_order.name, "Hacker in Rust");
   |    
fn your_order() {

       let order_template = create_order_template(); 

       let your_order = Order {

           name : String::from("Hacker in Rust"),

           .. order_template

       };

       assert_eq!(your_order.name, "Hacker in Rust");
}

thanks

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.