Skip to content

Instantly share code, notes, and snippets.

@Dobiasd
Created July 28, 2019 18:08
Show Gist options
  • Save Dobiasd/4d44fc681c6a51dc2e516f682e8e9366 to your computer and use it in GitHub Desktop.
Save Dobiasd/4d44fc681c6a51dc2e516f682e8e9366 to your computer and use it in GitHub Desktop.
struct Vector {
x: f64,
y: f64,
}
impl Vector {
fn length(&self) -> f64 {
return (self.x * self.x + self.y * self.y).sqrt();
}
fn normalize(&mut self) {
let l = self.length();
self.x /= l;
self.y /= l;
}
}
fn foo(v: &mut Vector) {
v.normalize();
}
fn bar(v: &Vector) {
v.normalize(); // -> Compiler error
println!("{}", v.length());
}
fn main() {
let mut my_vector = Vector { x: 3.0, y: 4.0 };
foo(&mut my_vector);
bar(&my_vector);
}
// error[E0596]: cannot borrow `*v` as mutable, as it is behind a `&` reference
// --> src/main.rs:23:5
// |
// | fn bar(v: &Vector) {
// | ------- help: consider changing this to be a mutable reference: `&mut Vector`
// | v.normalize();
// | ^ `v` is a `&` reference, so the data it refers to cannot be borrowed as mutable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment