Sub topic 2
Creating instances
This chapter assumes you can define a struct, write basic functions, and understand moves and borrows. Here you will learn how to build a value of a struct type, and which errors to expect when you get it wrong.
Struct literal syntax
You create an instance by naming the struct and giving a value 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);
}The order of fields in the literal does not need to match the definition. Each field is written as field: value, and you cannot list the same field twice.
Every field must be set
Rust has no default values for fields. If you leave one out, the compiler stops with error E0063:
error[E0063]: missing field `active` in initializer of `User`This rule means a User value can never exist in a half-built state. If you want defaults, you have to supply them yourself, through a constructor or through Default. Later chapters cover both.
Field init shorthand
When a variable has the same name as the field it fills, 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, means name: name,. You can mix shorthand and full field: value entries in the same literal, as the example does.
Ownership during construction
Building an instance moves each value into its field. After User { name, .. }, the variable name no longer owns its String, so using name afterward is a "borrow of moved value" error. If you still need the text, pass name.clone() or build the struct from a borrowed &str converted with to_string().
Copy types such as u32 and bool are copied, so the original variables stay usable.
Mutability belongs to the binding
Rust does not let you mark individual fields as mutable. The whole instance is either mutable or not, depending on how you bind it.
struct Counter {
count: u32,
}
fn main() {
let mut c = Counter { count: 0 };
c.count += 1;
println!("{}", c.count);
}Without mut on the let, the assignment c.count += 1 fails with "cannot assign to c.count, as c is not declared as mutable".
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| E0063 missing field | A field was left out of the literal | Supply every field |
| E0062 field specified more than once | A field name appears twice | Remove the duplicate |
| E0560 struct has no field named `x` | Typo or wrong struct | Check the definition |
| Borrow of moved value | A variable was moved into a field, then reused | Clone it, or reorder the code |
| Cannot assign to field | The binding is not `mut` | Declare it with `let mut` |
Exercise
Given struct Point { x: i32, y: i32 } and the variables let x = 3; let y = 4;, write a literal that builds a Point using field init shorthand. Then say why let p = Point { x, y }; p.x = 10; fails to compile.
Show answer
let p = Point { x, y }; builds the instance. The assignment p.x = 10; fails because p is bound without mut, and mutability applies to the whole instance. Writing let mut p = Point { x, y }; fixes it.