patternrustCritical
How I can mutate a struct's field from a method?
Viewed 0 times
howstructfieldfrommethodcanmutate
Problem
I want to do this:
But this code throws a compiler error:
struct Point {
x: i32,
y: i32,
}
impl Point {
fn up(&self) {
self.y += 1;
}
}
fn main() {
let p = Point { x: 0, y: 0 };
p.up();
}But this code throws a compiler error:
error[E0594]: cannot assign to field self.y of immutable binding
--> src/main.rs:8:9
|
7 | fn up(&self) {
| ----- use &mut self here to make mutable
8 | self.y += 1;
| ^^^^^^^^^^^ cannot mutably borrow field of immutable binding
Solution
You need to use
In Rust, mutability is inherited: the owner of the data decides if the value is mutable or not. References, however, do not imply ownership and hence they can be immutable or mutable themselves. You should read the official book which explains all of these basic concepts.
&mut self instead of &self and make the p variable mutable:struct Point {
x: i32,
y: i32,
}
impl Point {
fn up(&mut self) {
// ^^^ Here
self.y += 1;
}
}
fn main() {
let mut p = Point { x: 0, y: 0 };
// ^^^ And here
p.up();
}In Rust, mutability is inherited: the owner of the data decides if the value is mutable or not. References, however, do not imply ownership and hence they can be immutable or mutable themselves. You should read the official book which explains all of these basic concepts.
Code Snippets
struct Point {
x: i32,
y: i32,
}
impl Point {
fn up(&mut self) {
// ^^^ Here
self.y += 1;
}
}
fn main() {
let mut p = Point { x: 0, y: 0 };
// ^^^ And here
p.up();
}Context
Stack Overflow Q#27022848, score: 206
Revisions (0)
No revisions yet.