Skip to content
binshelf/ rust

Search lessons

Type a Rust, TypeScript or C# term, like Option, null or E0382.

    Compare Rust with

    Lessons

    Module 5 · Structs, methods & enums

    5.1Structs & impl blocks

    How Rust splits a class into a struct for the data and an impl block for the methods, and how self, &self and &mut self decide what a method may do with its value.

    About 25 minutesBeginner

    On this page
    1. Concept map
    2. A struct holds data, impl adds behavior
    3. :: for the type, . for a value
    4. Printing a struct
    5. self, &self and &mut self
    6. What self buys you
    7. Self or self?
    8. Struct update syntax
    9. Three kinds of struct
    10. No inheritance: put one struct inside another
    11. Who can see the fields
    12. Which one should I use?
    13. Under the hood
    14. Common pitfalls
    15. Try it yourself

    Concept map

    Concept map: how your language and Rust handle each idea in this lesson
    ConceptTypeScriptC#Rust
    A type with fields and methodsclass, or an interface plus functionsclass, struct or recordstruct for the fields, impl block for the methods
    Constructorconstructor(...), called with newA constructor or primary constructor, called with newA plain function, by convention new, called as Type::new(...)
    The object a method runs onthis, implicitthis, implicitself, &self or &mut self, written as the first parameter
    Static methodstatic methodstatic methodAssociated function: no self, called with ::
    Inheritanceclass B extends Aclass B : ANone. Put an A inside B, and share behavior with traits
    Print an object to debug itconsole.log(obj)ToString(), or a record's generated one#[derive(Debug)], then {:?}

    A TypeScriptC# class bundles three things: fields, methods and a constructor. Rust splits them up. A struct declares only the data. Methods live in a separate impl block. And there is no constructor at all, just ordinary functions that return a new value. The biggest change is that every method says, in its first parameter, what it does with the value it’s called on: read it, change it, or use it up.

    A struct holds data, impl adds behavior

    Here’s the same rectangle in both languages: two fields, a way to create one, and one method.

    TypeScript
    rectangle.ts
    class Rectangle {
      width: number;
      height: number;
    
      constructor(width: number, height: number) {
        this.width = width;
        this.height = height;
      }
    
      area(): number {
        return this.width * this.height;
      }
    }
    
    const rect = new Rectangle(3, 4);
    console.log(`${rect.width}x${rect.height} = ${rect.area()}`);
    C#
    Rectangle.cs
    var rect = new Rectangle(3, 4);
    Console.WriteLine($"{rect.Width}x{rect.Height} = {rect.Area()}");
    
    class Rectangle(int width, int height)
    {
        public int Width { get; } = width;
        public int Height { get; } = height;
    
        public int Area() => Width * Height;
    }
    Rust
    struct Rectangle {
        width: u32,
        height: u32,
    }
    
    impl Rectangle {
        fn new(width: u32, height: u32) -> Self {
            Self { width, height }
        }
    
        fn area(&self) -> u32 {
            self.width * self.height
        }
    }
    
    fn main() {
        let rect = Rectangle::new(3, 4);
        println!("{}x{} = {}", rect.width, rect.height, rect.area());
    }

    Output

    3x4 = 12

    Read the Rust version from the top:

    • struct Rectangle lists the fields and their types. Nothing else goes in it.
    • impl Rectangle holds the functions that belong to the type. A type can have several impl blocks.
    • fn new is not special. new isn’t a keyword, just the name everyone uses. It builds a value with a struct literal, Self { width, height }, and returns it.
    • Self (capital S) is shorthand for the type the impl is for, here Rectangle.
    • Self { width, height } uses field init shorthand: when a variable has the same name as the field, width means width: width. TypeScript object literals have the same shorthand.C# anonymous types have a similar shorthand: new { width, height }.
    • fn area(&self) is a method. Its first parameter, &self, is the rectangle it was called on, borrowed for reading.

    Mental model shiftThere is no constructor

    Rust has no new operator and no constructor that runs automatically. Any code can build a Rectangle with a struct literal, Rectangle { width: 3, height: 4 }, as long as it can see the fields. Rectangle::new(3, 4) is a regular function that does exactly that. You can write several, such as new, square(size) or with_capacity(n), instead of overloading one constructor.

    :: for the type, . for a value

    Rectangle::new(3, 4) uses :: because there’s no rectangle yet: you’re asking the type. rect.area() uses . because it runs on an existing value. Functions without self are called associated functions. They’re Rust’s static methods.

    Printing a struct

    TypeScript’s console.log prints any object.A C# record prints its fields through its generated ToString(), and a class prints only its type name. A Rust struct can’t be printed until you ask the compiler to generate the code with #[derive(Debug)]. Then {:?} prints it on one line and {:#?} prints it spread over several:

    #[derive(Debug)]
    struct Point {
        x: i32,
        y: i32,
    }
    
    let point = Point { x: 1, y: 2 };
    println!("{point:?}"); // Point { x: 1, y: 2 }
    println!("{point:#?}"); // the same, one field per line

    Debug output is for developers. Output for users comes from implementing the Display trait, which Module 9 covers along with the other standard traits.

    self, &self and &mut self

    In a TypeScriptC# class, this is always there and always the same thing: a reference to the object, which any method can read and change. In Rust you choose, for each method, one of three receivers as the first parameter:

    ReceiverShort forThe method getsLike
    &selfself: &SelfA shared borrow: it can read the fieldsA C# readonly member of a structA method that only reads this, though nothing checks that
    &mut selfself: &mut SelfAn exclusive borrow: it can read and change the fieldsA normal TypeScriptC# method that changes a field
    selfself: SelfThe value itself, moved in: it owns it from now onNo TypeScriptC# equivalent

    This shopping cart uses all three:

    TypeScript
    cart.ts
    class Cart {
      customer: string;
      items: string[] = [];
    
      constructor(customer: string) {
        this.customer = customer;
      }
    
      add(item: string): void {
        this.items.push(item);
      }
    
      count(): number {
        return this.items.length;
      }
    
      checkout(): string {
        return `${this.customer} ordered ${this.items.join(", ")}`;
      }
    }
    
    const cart = new Cart("Ada");
    cart.add("apple");
    cart.add("pear");
    console.log(cart.count());
    console.log(cart.checkout());
    C#
    Cart.cs
    var cart = new Cart("Ada");
    cart.Add("apple");
    cart.Add("pear");
    Console.WriteLine(cart.Count());
    Console.WriteLine(cart.Checkout());
    
    class Cart(string customer)
    {
        private readonly List<string> items = [];
    
        public void Add(string item) => items.Add(item);
    
        public int Count() => items.Count;
    
        public string Checkout() => $"{customer} ordered {string.Join(", ", items)}";
    }
    Rust
    struct Cart {
        customer: String,
        items: Vec<String>,
    }
    
    impl Cart {
        fn new(customer: &str) -> Self {
            Self {
                customer: customer.to_string(),
                items: Vec::new(),
            }
        }
    
        fn add(&mut self, item: &str) {
            self.items.push(item.to_string());
        }
    
        fn count(&self) -> usize {
            self.items.len()
        }
    
        fn checkout(self) -> String {
            format!("{} ordered {}", self.customer, self.items.join(", "))
        }
    }
    
    fn main() {
        let mut cart = Cart::new("Ada");
        cart.add("apple");
        cart.add("pear");
        println!("{}", cart.count());
        println!("{}", cart.checkout());
    }

    Output

    2
    Ada ordered apple, pear
    • count(&self) only reads, so it borrows. You can call it as often as you like.
    • add(&mut self, ...) changes items, so it needs an exclusive borrow. That’s why main declares let mut cart: you can only borrow a value mutably if its variable is mut.
    • checkout(self) takes the cart itself. The cart moves into the method, and is dropped when the method returns. After cart.checkout(), cart is gone.

    All three are called the same way, with a dot. Rust borrows for you: cart.count() passes &cart, cart.add("pear") passes &mut cart, and cart.checkout() passes cart itself.

    What self buys you

    In TypeScriptC#, nothing stops you adding to a cart after checking it out. The TypeScriptC# version below runs and prints 2: the pear went into an order that was already placed. Rust won’t compile it, because checkout took ownership of the cart:

    TypeScript
    cart.ts
    const cart = new Cart("Ada");
    cart.add("apple");
    const order = cart.checkout();
    cart.add("pear"); // too late, but nothing stops it
    console.log(cart.count());
    C#
    Cart.cs
    var cart = new Cart("Ada");
    cart.Add("apple");
    var order = cart.Checkout();
    cart.Add("pear"); // too late, but nothing stops it
    Console.WriteLine(cart.Count());
    
    Rust
    let mut cart = Cart::new("Ada");
    cart.add("apple");
    let order = cart.checkout();
    cart.add("pear");

    Output of the TypeScriptC# version

    2

    Rust doesn't compile this: error E0382

    error[E0382]: borrow of moved value: `cart`
      --> cart.rs:4:1
       |
     1 | let mut cart = Cart::new("Ada");
       |     -------- move occurs because `cart` has type `Cart`, which does not implement the `Copy` trait
     2 | cart.add("apple");
     3 | let order = cart.checkout();
       |                  ---------- `cart` moved due to this method call
     4 | cart.add("pear");
       | ^^^^ value borrowed here after move
       |
    note: `Cart::checkout` takes ownership of the receiver `self`, which moves `cart`
      --> cart.rs
       |
       |     fn checkout(self) -> String {
       |                 ^^^^

    To get this guarantee in TypeScriptC#, you’d add a checkedOut flag and throw an exception at run time.

    Here’s the cart’s whole life with all three receivers. Each borrow lasts only for its call, and checkout ends the cart:

    let mut cart = Cart::new("Ada");
    cart.add("apple");
    println!("{}", cart.count());
    let order = cart.checkout();
    println!("{order}");
    cart.add("pear");

    Rust doesn't compile this: error E0382

    error[E0382]: borrow of moved value: `cart`
      --> main.rs:6:1
       |
     1 | let mut cart = Cart::new("Ada");
       |     -------- move occurs because `cart` has type `Cart`, which does not implement the `Copy` trait
    ...
     4 | let order = cart.checkout();
       |                  ---------- `cart` moved due to this method call
     5 | println!("{order}");
     6 | cart.add("pear");
       | ^^^^ value borrowed here after move
       |
    note: `Cart::checkout` takes ownership of the receiver `self`, which moves `cart`
      --> main.rs
       |
       |     fn checkout(self) -> String {
       |                 ^^^^
    One cart, three kinds of method call
    One cart, three kinds of method call. Each column is a value or a borrow; a mark means it's alive on that line.
    LineCodecartowner&mut cartmutable borrow (&mut)&cartshared borrow (&)orderownercartmoved outWhat happens
    1let mut cart = Cart::new("Ada");ownscart startscart owns the new Cart.
    2cart.add("apple");cart alive&mut&mut cart startsadd(&mut self) borrows cart mutably, only for this call.
    3println!("{}", cart.count());cart alive&&cart startscount(&self) borrows cart, only for this call.
    4let order = cart.checkout();cart endsownsorder startscheckout(self) takes cart itself: it moves into the method.
    5println!("{order}");order alivemovedcart startsorder owns the String that checkout returned.
    6cart.add("pear");order endscart endserrorcart was moved into checkout on line 4 (E0382).

    Six lines using one cart. cart owns its Cart from line 1 to line 4. On line 2, add takes &mut self, so cart is borrowed mutably for that call only. On line 3, count takes &self, so cart is borrowed for that call only. On line 4, checkout takes self, so cart moves into the method, and order owns the String it returns from then on. From line 5, cart is moved out, so calling add on it on line 6 is a compile error.

    Caught at compile timeUse after consume

    A method that takes self turns “don’t use this after X” into a rule the compiler checks. Builders (.build()), conversions (.into_bytes()) and state changes (.checkout()) use it so the old value can’t be reused by mistake. The error is the same E0382 you met in Ownership and move semantics: calling the method moved the value.

    Self or self?

    • Self, capital S, is a type: the one the impl block is for. Use it in return types and struct literals, as in fn new() -> Self. TypeScriptC# has no shorthand for this; you repeat the class name.
    • self, lowercase, is a value: the receiver, like this. Use it to reach fields, as in self.width. Unlike C#, youAs with this in TypeScript, you can’t leave it out: width on its own is not the field.
    TypeScript has a feature that looks just like a Rust receiver: a fake first parameter that types this, as in function area(this: Rectangle). In Rust that first parameter is real, and its type says whether it borrows, borrows mutably or takes ownership.
    A C# extension method looks a lot like a Rust method: the receiver is an explicit first parameter, as in static int Area(this Rectangle rect). In Rust every method works that way, and the receiver’s type says whether it borrows, borrows mutably or takes ownership.

    Struct update syntax

    To build a struct that’s mostly the same as another, TypeScript spreads an objectC# uses a record’s with expression. Rust writes ..other last in the struct literal:

    TypeScript
    config.ts
    type Config = { host: string; port: number; timeoutSecs: number };
    
    const defaults: Config = { host: "localhost", port: 80, timeoutSecs: 30 };
    const dev: Config = { ...defaults, port: 8080 };
    console.log(`${dev.host}:${dev.port}, timeout ${dev.timeoutSecs}s`);
    C#
    Config.cs
    var defaults = new Config("localhost", 80, 30);
    var dev = defaults with { Port = 8080 };
    Console.WriteLine($"{dev.Host}:{dev.Port}, timeout {dev.TimeoutSecs}s");
    
    record Config(string Host, int Port, int TimeoutSecs);
    Rust
    struct Config {
        host: String,
        port: u16,
        timeout_secs: u32,
    }
    
    fn main() {
        let defaults = Config {
            host: String::from("localhost"),
            port: 80,
            timeout_secs: 30,
        };
        let dev = Config {
            port: 8080,
            ..defaults
        };
        println!("{}:{}, timeout {}s", dev.host, dev.port, dev.timeout_secs);
    }

    Output

    localhost:8080, timeout 30s

    The fields you list win, and the rest come from defaults. Unlike a spreadwith, which copies, ..defaults moves each field it takes. Here it takes host and timeout_secs. timeout_secs is a number, so it’s copied. host is a String, so it moves into dev. Now defaults is partially moved: defaults.port and defaults.timeout_secs still work, but defaults.host and defaults as a whole can’t be used. The pitfalls below show the fix.

    Three kinds of struct

    Besides structs with named fields, there are two shorter forms:

    struct Point {
        x: i32,
        y: i32,
    } // named fields
    
    struct Meters(f64); // tuple struct: fields by position
    
    struct Unlimited; // unit struct: no fields at all
    
    let point = Point { x: 1, y: 2 };
    let height = Meters(1.8);
    let plan = Unlimited;
    println!("{} {} {}", point.x, point.y, height.0); // tuple fields are .0, .1, ...

    A tuple struct with one field is called a newtype. It costs nothing at run time (a Meters is just an f64), but the compiler treats it as a different type, so you can’t mix up IDs or units:

    struct UserId(u32);
    struct OrderId(u32);
    
    fn find_user(id: UserId) -> u32 {
        id.0
    }
    
    fn main() {
        let order = OrderId(7);
        find_user(order);
    }

    Rust doesn't compile this: error E0308

    error[E0308]: mismatched types
      --> main.rs:10:15
       |
    10 |     find_user(order);
       |     --------- ^^^^^ expected `UserId`, found `OrderId`
       |     |
       |     arguments to this function are incorrect
       |
    note: function defined here
      --> main.rs:4:4
       |
     4 | fn find_user(id: UserId) -> u32 {
       |    ^^^^^^^^^ ----------
    In TypeScript, type UserId = number is just another name for number, so the mix-up compiles. You’d need a “branded” type to catch it.
    In C#, a readonly record struct UserId(int Value) gives you the same protection as a Rust newtype.

    A unit struct has no data and takes no memory. It’s useful as a marker that implements traits, which Module 9 covers.

    No inheritance: put one struct inside another

    Rust structs can’t extend each other. Where TypeScript would write class Admin extends UserC# would write class Admin : User, Rust puts a User inside the Admin as a field:

    struct User {
        name: String,
    }
    
    impl User {
        fn greet(&self) -> String {
            format!("Hi, {}", self.name)
        }
    }
    
    struct Admin {
        user: User,
        level: u8,
    }
    
    fn main() {
        let admin = Admin {
            user: User {
                name: String::from("Ada"),
            },
            level: 2,
        };
        println!("{} (level {})", admin.user.greet(), admin.level); // Hi, Ada (level 2)
    }

    An Admin has a User rather than being one, so you write admin.user.greet(). If you want admin.greet(), add a one-line method to Admin that calls self.user.greet().

    Mental model shiftComposition and traits replace inheritance

    Inheritance does two jobs: it reuses fields and code, and it lets one function accept many types. Rust splits them. Fields are reused by putting one struct inside another. Shared behavior comes from traits, Rust’s version of interfaces, which any struct or enum can implement. Module 9 covers traits.

    Who can see the fields

    Fields and methods are private to their module unless you mark them pub. Every example in this lesson is one module, so it can use every field. Once you split code into modules, other modules can’t read rect.width or call Rectangle::new without pub. Module 7 covers modules and visibility.

    Which one should I use?

    Every method starts with this choice, and the compiler checks every caller against it.

    WhatWhenWhyHow
    &self (read)The method only reads fields: getters, calculations, formatting.The caller keeps the value, and any number of readers can borrow it at once.fn count(&self) -> usize, called cart.count(). Works on let and let mut variables.
    &mut self (change)The method changes fields in place: add, remove, increment, set.It gets exclusive access while it runs, and the caller still owns the value afterwards.fn add(&mut self, item: &str), called cart.add("pear"). The variable must be let mut.
    self (consume)The value shouldn’t be used after the call: it’s turned into something else, handed off, or finished.Ownership moves into the method, so it can move fields out without cloning, and the compiler blocks any later use.fn checkout(self) -> String, called cart.checkout(). cart is gone afterwards.
    No self (associated function)Constructors and helpers that don’t start from an existing value.There’s no value yet to call it on.fn new(customer: &str) -> Self, called Cart::new("Ada") with ::.

    Rule of thumb: start with &self. Switch to &mut self when the method has to change a field. Take self only when the value shouldn’t exist after the call. Constructors are associated functions named new, or with_… and from_… when you need more than one.

    Which kind of struct to declare:

    WhatWhenWhyHow
    Named fieldsAlmost always: anything with more than one field.Names document what each field means.struct Point { x: i32, y: i32 }, read as point.x.
    Tuple struct (newtype)Wrapping one value to give it its own type: IDs, units, validated strings.The compiler stops you passing an OrderId where a UserId goes, at no run-time cost.struct UserId(u32);, read as id.0.
    Unit structA type that needs no data, only behavior or a name.It takes no memory.struct Unlimited;, created as Unlimited.

    Under the hood

    A struct is just its fields, laid out next to each other. There’s no object header, no type pointer and no heap allocation unless a field owns one (like a String). A Rectangle is two u32s, 8 bytes, and a local Rectangle lives entirely on the stack. A C# class instance, by contrast, sits on the heap behind a header, and the variable holds a reference to it.A TypeScript object, by contrast, is a JavaScript object on the heap with engine bookkeeping in front of its fields, and the variable holds a reference to it.

    A method is an ordinary function with the receiver as its first argument. These two calls are the same call:

    let rect = Rectangle {
        width: 3,
        height: 4,
    };
    let a = rect.area();
    let b = Rectangle::area(&rect); // what rect.area() means
    assert_eq!(a, b);
    assert_eq!(size_of::<Rectangle>(), 8); // just the two u32 fields
    Inside rect.area()On the stack, rect is a Rectangle holding width 3 and height 4 directly, with nothing on the heap. While area runs, its parameter self is a &Rectangle: a single pointer to rect. Nothing was copied and rect still owns its data.Stackrect: Rectanglewidth3height4self: &Rectangleptr
    Inside rect.area(). On the stack, rect is a Rectangle holding width 3 and height 4 directly, with nothing on the heap. While area runs, its parameter self is a &Rectangle: a single pointer to rect. Nothing was copied and rect still owns its data.

    The compiler knows the exact type of rect, so rect.area() is a direct call that can be inlined. There’s no virtual dispatch and no vtable. Rust only adds those when you ask for them, with trait objects (Module 9). &mut self is also a pointer, and self moves the struct’s bytes into the method, the same cheap move as passing a String.

    A struct inside another struct is stored inline too. The Admin from earlier holds its User’s bytes directly, not a pointer to a separate object. The compiler also adds padding, so every Admin in an array starts on the 8-byte boundary its String needs. These sizes are what today’s compiler produces on a 64-bit target:

    assert_eq!(size_of::<User>(), 24); // one String: pointer, capacity, length
    assert_eq!(size_of::<Admin>(), 32); // the User, the u8, then 7 bytes of padding
    An Admin in memory
    An Admin in memory: each row is one value; each cell's width is its size in bytes.
    Value012345678910111213141516171819202122232425262728293031Size
    Adminuser: User (its name String)24 byteslevel: u81 bytepadding7 bytes32 bytes

    Today, on a 64-bit target, an Admin takes 32 bytes, shown here in one possible order. The first 24 bytes are the user field: the whole User struct stored inline, which is its name String (a pointer, a capacity and a length). Then 1 byte for level, a u8. The last 7 bytes are padding that round the size up to a multiple of 8. Rust may reorder fields, so the order in memory isn't guaranteed.

    Common pitfalls

    Common pitfallForgetting mut for a &mut self method

    add takes &mut self, so the cart’s variable must be mut. In TypeScript, const only stops you reassigning the variable, and you can still change the object.In C#, a variable never stops you changing the object it refers to; even a readonly field only stops reassignment. In Rust, let without mut also stops you changing the value’s fields:

    let cart = Cart { items: Vec::new() };
    cart.add("apple");

    Rust doesn't compile this: error E0596

    error[E0596]: cannot borrow `cart` as mutable, as it is not declared as mutable
      --> main.rs:2:1
       |
     2 | cart.add("apple");
       | ^^^^ cannot borrow as mutable
       |
    help: consider changing this to be mutable
       |
     1 | let mut cart = Cart { items: Vec::new() };
       |     +++

    Fix it with let mut cart.

    Common pitfallWriting self when you meant &self

    Leave out the & and the method takes ownership. The first call works, and the second fails, because the first one used the value up:

    impl Rectangle {
        fn area(self) -> u32 {
            self.width * self.height
        }
    }
    
    let rect = Rectangle {
        width: 3,
        height: 4,
    };
    println!("{}", rect.area());
    println!("{}", rect.area());

    Rust doesn't compile this: error E0382

    error[E0382]: use of moved value: `rect`
      --> main.rs:12:16
       |
     7 | let rect = Rectangle {
       |     ---- move occurs because `rect` has type `Rectangle`, which does not implement the `Copy` trait
    ...
    11 | println!("{}", rect.area());
       |                     ------ `rect` moved due to this method call
    12 | println!("{}", rect.area());
       |                ^^^^ value used here after move
       |
    note: `Rectangle::area` takes ownership of the receiver `self`, which moves `rect`
      --> main.rs:2:13
       |
     2 |     fn area(self) -> u32 {
       |             ^^^^

    A method that only reads should take &self.

    Common pitfallFields need self.

    C# lets you write Width inside a method and means this.Width.TypeScript already makes you write this.width, and Rust is just as strict. Rust never adds self for you, so a bare width is looked up as a local variable:

    impl Rectangle {
        fn area(&self) -> u32 {
            width * height
        }
    }

    Rust doesn't compile this: error E0425

    error[E0425]: cannot find value `width` in this scope
     --> main.rs:3:9
      |
    3 |         width * height
      |         ^^^^^
      |
    help: you might have meant to use the available field
      |
    3 |         self.width * height
      |         +++++
    
    error[E0425]: cannot find value `height` in this scope
     --> main.rs:3:17
      |
    3 |         width * height
      |                 ^^^^^^
      |
    help: you might have meant to use the available field
      |
    3 |         width * self.height
      |                 +++++

    Common pitfall..other moves the fields it takes

    Struct update syntax moves non-Copy fields, such as a String, out of the old value. Reading them afterwards fails:

    let defaults = Config {
        host: String::from("localhost"),
        port: 80,
    };
    let dev = Config {
        port: 8080,
        ..defaults
    };
    println!("{} {}", dev.host, defaults.host);

    Rust doesn't compile this: error E0382

    error[E0382]: borrow of moved value: `defaults.host`
      --> main.rs:9:29
       |
     5 |   let dev = Config {
       |  _______________-
     6 | |         port: 8080,
     7 | |         ..defaults
     8 | |     };
       | |_____- value moved here
     9 |   println!("{} {}", dev.host, defaults.host);
       |                               ^^^^^^^^^^^^^ value borrowed here after move
       |
       = note: move occurs because `defaults.host` has type `String`, which does not implement the `Copy` trait
       = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)

    If you still need defaults, copy the field yourself with host: defaults.host.clone(), or derive Clone and write ..defaults.clone().

    Try it yourself

    Exercise: port this to Rust

    Port this bank account to Rust. Give each method the receiver it needs, so that an account can’t be used after it’s closed.

    Starting code in TypeScript
    account.ts
    class Account {
      owner: string;
      balance: number;
    
      constructor(owner: string) {
        this.owner = owner;
        this.balance = 0;
      }
    
      deposit(amount: number): void {
        this.balance += amount;
      }
    
      close(): string {
        return `${this.owner} closed with ${this.balance}`;
      }
    }
    
    const account = new Account("Ada");
    account.deposit(50);
    account.deposit(25);
    console.log(account.balance);
    console.log(account.close());
    Starting code in C#
    Account.cs
    var account = new Account("Ada");
    account.Deposit(50);
    account.Deposit(25);
    Console.WriteLine(account.Balance);
    Console.WriteLine(account.Close());
    
    class Account(string owner)
    {
        public int Balance { get; private set; }
    
        public void Deposit(int amount) => Balance += amount;
    
        public string Close() => $"{owner} closed with {Balance}";
    }

    Expected output

    75
    Ada closed with 75
    Show a hint

    deposit changes the balance, so it takes &mut self and the variable needs mut. balance only reads, so it takes &self. close should use the account up, so it takes self.

    Show a solution
    struct Account {
        owner: String,
        balance: u64,
    }
    
    impl Account {
        fn new(owner: &str) -> Self {
            Self {
                owner: owner.to_string(),
                balance: 0,
            }
        }
    
        fn balance(&self) -> u64 {
            self.balance
        }
    
        fn deposit(&mut self, amount: u64) {
            self.balance += amount;
        }
    
        fn close(self) -> String {
            format!("{} closed with {}", self.owner, self.balance)
        }
    }
    
    fn main() {
        let mut account = Account::new("Ada");
        account.deposit(50);
        account.deposit(25);
        println!("{}", account.balance());
        println!("{}", account.close());
    }

    new is an associated function that returns Self. balance and deposit borrow the account, so main can keep calling them. close takes self, so the account is moved into it and any use of account after close would fail to compile with E0382, which is what you want for a closed account.

    Saved in this browser only.