Back to questions
JuniorTheoryCommon
What happens when this program is built and run?
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 1, y: 2 };
p.x = 5;
println!("{} {}", p.x, p.y);
}It does not compile
- Expecting
5 2, as with aconstobject in JavaScript: in Rustmutcovers the whole variable, so withoutlet mut pno field ofpcan be assigned (E0594). - Expecting a panic at run time: mutability is checked while building, so the compiler rejects
p.x = 5and no program is produced.
- What is the smallest change that makes this program print
5 2? - Can you make only the field
xmutable whileystays read-only?