Structs
| Define a struct | |
| Initialize | |
| Update syntax | |
| Tuple structs |
Define a struct
A struct groups named fields under one type. Each field has a name and a type, owned or borrowed:
struct User {
name: String,
age: u32,
}
Initialize
Build a struct by naming each field with its value. Shorthand allows a variable with the same name to fill its field directly:
let name = String::from("Ada");
let me = User { name, age: 36 };
Update syntax
Update syntax copies remaining fields from another value. It keeps code short when only one or two fields change:
let other = User { name: String::from("Bo"), age: 28 };
let newer = User { age: 29, ..other };
Tuple structs
A tuple struct names a shape without naming fields. It fits newtypes and simple pairs where position is enough:
struct Point(i32, i32);
let p = Point(3, 4);
Next: Enums
Article author: Arthur Isaev