这是使可变变量在rust中再次不可变的正确方法吗?
我已经创建了一个简单的列表,它具有可变的推送行为,但对于peek fn不需要具有相同的可变性这是使可变变量在rust中再次不可变的正确方法吗?,rust,ownership,Rust,Ownership,我已经创建了一个简单的列表,它具有可变的推送行为,但对于peek fn不需要具有相同的可变性 fn peek(){ let mut list = List::new();//take a mutable ref here to perform push list.push(1); let list = list; //shadow the variable with the same name and take a immut ref
fn peek(){
let mut list = List::new();//take a mutable ref here to perform push
list.push(1);
let list = list; //shadow the variable with the same name and take a immut ref
assert_eq!(list.peek().unwrap(),&1);
}
你的方式很好。通常包括这样的评论:
let list = list; // discard mut
另一种方法是分离初始化(它是否更好,复杂性与可读性与关注点的分离是有争议的)
fn peek() {
let list = {
let mut list = List::new();
list.push(1);
list
};
assert_eq!(list.peek().unwrap(),&1);
}
你的方式很好。通常包括这样的评论:
let list = list; // discard mut
另一种方法是分离初始化(它是否更好,复杂性与可读性与关注点的分离是有争议的)
fn peek() {
let list = {
let mut list = List::new();
list.push(1);
list
};
assert_eq!(list.peek().unwrap(),&1);
}
你的解决方案是正确的。这样做可能更具可读性:
fn peek(){
let list = {
let mut li = List::new();//take a mutable ref here to perform push
li.push(1);
li
};
assert_eq!(list.peek().unwrap(),&1);
}
但在您的情况下,还有另一种选择:
fn peek(){
let list = std::iter::once(1).collect::<List<_>>();
assert_eq!(list.peek().unwrap(),&1);
}
fn peek(){
let list=std::iter::once(1)。collect::();
断言(list.peek().unwrap(),&1);
}
您的解决方案足够正确。这样做可能更具可读性:
fn peek(){
let list = {
let mut li = List::new();//take a mutable ref here to perform push
li.push(1);
li
};
assert_eq!(list.peek().unwrap(),&1);
}
但在您的情况下,还有另一种选择:
fn peek(){
let list = std::iter::once(1).collect::<List<_>>();
assert_eq!(list.peek().unwrap(),&1);
}
fn peek(){
let list=std::iter::once(1)。collect::();
断言(list.peek().unwrap(),&1);
}
从副本中:“降级”可变绑定到不可变绑定在Rust中非常常见。所以是的,这很正常。@trentcl是的,谢谢!!从副本来看,“降级”可变绑定到不可变绑定在Rust中非常常见。所以是的,这很正常。@trentcl是的,谢谢!!