> cargo builderror[E0515]: cannot return reference to local data `node.elem`--> src/second.rs:37:13|37|&node.elem|^^^^^^^^^^ returns a reference to data owned by the current functionerror[E0507]: cannot move out of borrowed content--> src/second.rs:36:9|36| self.head.map(|node| {|^^^^^^^^^ cannot move out of borrowed content
#[test]fnpeek() {letmut list =List::new();assert_eq!(list.peek(), None);assert_eq!(list.peek_mut(), None); list.push(1); list.push(2); list.push(3);assert_eq!(list.peek(), Some(&3));assert_eq!(list.peek_mut(), Some(&mut3)); list.peek_mut().map(|&mut value| { value =42 });assert_eq!(list.peek(), Some(&42));assert_eq!(list.pop(), Some(42));}
> cargo testerror[E0384]: cannot assign twice to immutable variable `value`--> src/second.rs:100:13|99| list.peek_mut().map(|&mut value| {|-----||| first assignment to `value`| help: make this binding mutable: `mut value`100| value =42|^^^^^^^^^^ cannot assign twice to immutable variable ^~~~~
编译器抱怨值是不可变的,但是我们很清楚地写下了&mut value;给出了什么?事实证明,以这种方式编写闭包的参数并没有指定值是可变引用。相反,它会创建一个模式,该模式将与闭包的参数相匹配;|&mut value |意味着“参数是一个可变的引用,但是请将它指向的值复制到value中”。如果我们只使用 |value |,那么值的类型将是&mut i32,我们实际上可以改变head: