Introduction
Accessing fields lets you get or change the information stored inside a data structure like a struct.
struct StructName {
field_name: FieldType,
// other fields
}
let instance = StructName { field_name: value, /* ... */ };
// Access field
let value = instance.field_name;pub) if accessed from another module.name field of the person instance to print it.struct Person {
name: String,
age: u32,
}
let person = Person { name: String::from("Alice"), age: 30 };
println!("Name: {}", person.name);x field of a mutable struct instance.struct Point {
x: i32,
y: i32,
}
let mut point = Point { x: 5, y: 10 };
point.x = 15; // change x value
println!("Point is at ({}, {})", point.x, point.y);Car struct and prints its fields by accessing them.struct Car {
make: String,
year: u32,
}
fn main() {
let car = Car { make: String::from("Toyota"), year: 2020 };
println!("Car make: {}", car.make);
println!("Car year: {}", car.year);
}age of a struct instance named person?person and field age, the correct syntax is person.age.color in Rust?Car is correctly defined with a field color of type String. The instance my_car is created with color: String::from("red"), which is correct.my_car.color, which is the correct way to access struct fields in Rust.struct Point { x: i32, y: i32 }
fn main() {
let p = Point { x: 10, y: 20 };
println!("{}", p.x + p.y);
}Point has fields x and y with values 10 and 20 respectively.p.x and p.y, which is 10 + 20 = 30.struct User { name: String, age: u32 }
fn main() {
let user = User { name: String::from("Alice"), age: 30 };
println!("{}", user->name);
}user->name which is invalid in Rust. Rust uses dot (.) to access fields.struct Product { name: String, price: f64, discount: Option<f64> }
fn main() {
let p = Product { name: String::from("Book"), price: 30.0, discount: Some(5.0) };
let final_price = match p.discount {
Some(d) => p.price - d,
None => p.price,
};
println!("{} costs ${}", p.name, final_price);
}Product instance p has price 30.0 and discount Some(5.0).Book costs $25.Pass the test and this pattern moves unknown