The question arises from following code:
#[derive(Debug)]
struct Foo {
x: i32,
}
pub fn main() {
let a = vec![Foo{x:1}, Foo{x:2}];
println!("{:?}", a[1]);
println!("{:?}", &a[1]);
println!("{:?}", *(&a[1]));
}
After cargo run
, the code outputs:
Foo { x: 2 }
Foo { x: 2 }
Foo { x: 2 }
Which caused me wondering:
- Why
println!("{:?}", a[1])
won't take ownership of 2nd element? - What are differences between passing by reference and by value under this circumstance?
- Is it possible to implement similar functions capable of accepting parameters by value(without taking ownership) and by reference, without resorting to macro system?