Sub topic 2
Creating Instances
This chapter assumes you can already define a struct with named fields and that you know Rust's move and borrow rules. It covers how to build a value of a struct type, what the compiler checks when you do, and which errors you will see most often.
The struct literal
You create an instance with a struct literal. It is the struct's name followed by braces that contain a field: value pair for every field.
#[derive(Debug)]
struct User {
name: String,
email: String,
age: u32,
active: bool,
}
fn main() {
let user = User {
name: String::from("Ada"),
email: String::from("[email protected]"),
age: 36,
active: true,
};
println!("{:?}", user);
}A struct literal is an expression. It produces a value of type User, so you can bind it with let, return it from a function, or pass it straight into another call.
Three rules apply:
- Every field must be given a value. Rust has no implicit defaults and no uninitialized fields.
- Each field can appear only once.
- Each value must have exactly the field's declared type. Rust does not convert types for you here, so an integer literal cannot become a
String, and a&strcannot stand in for aString.
Field order does not matter
You can write the fields in any order. The compiler matches them by name, not by position.
Evaluation order is a separate matter. The expressions you write run in the order they appear in the literal, not in the order the struct declares its fields. The next program shows the difference.
struct Pair {
first: i32,
second: i32,
}
fn show(label: &str, n: i32) -> i32 {
println!("evaluating {label}");
n
}
fn main() {
let p = Pair {
second: show("second", 2),
first: show("first", 1),
};
println!("{} {}", p.first, p.second);
}It prints evaluating second, then evaluating first, then 1 2. This rarely matters for plain values. It matters when the field expressions have side effects, such as reading input or pulling items from an iterator.
Field init shorthand
Constructor functions often take parameters named after the fields. When a variable has the same name as the field it initializes, you can write the name once.
#[derive(Debug)]
struct User {
name: String,
email: String,
age: u32,
active: bool,
}
fn make_user(name: String, email: String) -> User {
User {
name,
email,
age: 18,
active: true,
}
}
fn main() {
let user = make_user(String::from("Grace"), String::from("[email protected]"));
println!("{:?}", user);
}name, is exactly the same as name: name,. You can mix shorthand and full pairs in one literal. The shorthand only works with a plain variable name. For anything else, such as name: name.trim().to_string(), write the whole pair.
Moves and copies into fields
Building a struct moves each value into its field. This follows the ordinary ownership rules.
- A
Copytype, such asu32orbool, is copied. The original variable stays usable. - A non-
Copytype, such asStringorVec<T>, is moved. The original variable can no longer be used.
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
#[derive(Debug)]
struct Label {
text: String,
at: Point,
}
fn main() {
let text = String::from("origin");
let label = Label {
text,
at: Point { x: 0, y: 0 },
};
// println!("{}", text); // error[E0382]: borrow of moved value: `text`
println!("{:?}", label);
}The example also shows nesting. A field can hold another struct, and you build the inner value with its own literal inside the outer one.
Mutability belongs to the binding
Rust has no per-field mut in a struct definition. Whether you can change a field depends on how the instance is bound.
struct Counter {
count: u32,
}
fn main() {
let c = Counter { count: 0 };
// c.count += 1; // error[E0594]: cannot assign to `c.count`, as `c` is not declared as mutable
let mut m = Counter { count: 0 };
m.count += 1;
println!("{}", m.count);
let _ = c;
}If you write let mut, the whole instance is mutable. If you write plain let, none of it is. The next chapter covers changing and borrowing individual fields in detail.
Common errors
The compiler checks struct literals closely. These are the errors you will meet most often.
| Mistake | Typical error | Fix |
|---|---|---|
| Leaving out a field | E0063: missing field `age` in initializer of `User` | Supply the field, or use struct update syntax (next chapter) |
| Naming a field that does not exist | E0560: struct `User` has no field named `nickname` | Check the spelling against the definition |
| Giving a field twice | E0062: field `age` specified more than once | Remove the duplicate |
| Wrong type, such as `name: "Ada"` | E0308: mismatched types, expected `String`, found `&str` | Use `String::from("Ada")` or `"Ada".to_string()` |
| Using a variable after it was moved in | E0382: borrow of moved value | Clone it, or restructure so you do not need it |
| Building a struct with private fields from another module | E0451: field `balance` of struct `Account` is private | Use a public constructor function |
The last row matters for design. A struct literal needs access to every field. If any field is private, code outside the defining module cannot use a literal at all. That is how a module forces callers through its constructors, and it is why a later chapter on privacy pairs with associated functions.
Choosing between a literal and a constructor
Use a literal directly when a struct is a simple bag of data and every field is meaningful to the caller. Use a constructor function, called new by convention, when:
- some fields have fixed starting values, such as a counter that begins at 0
- the struct has private fields
- you need to validate input before the value exists
A constructor is an ordinary function that contains a struct literal. Everything in this chapter applies inside it.
Exercise
This code does not compile. Name two separate problems, then fix them. struct Item { label: String, qty: u32, } fn main() { let label = String::from("bolt"); let item = Item { label: "nut", qty: 4, }; println!("{} {}", label, item.qty); }
Show answer
The first problem is label: "nut". The field is a String, but "nut" is a &str, which gives a mismatched types error. Write label: String::from("nut"). The second problem is the unused local label, which is not an error but suggests the intent was shorthand. If you want item.label to hold the local, write Item { label, qty: 4 }. In that case label is moved, so print item.label instead of the local variable. A working version is: let item = Item { label, qty: 4 }; println!("{} {}", item.label, item.qty);