I've created a simple list that has mutable push behaviour but no need to have that same mutability for 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
assert_eq!(list.peek().unwrap(),&1);
}
Your way is fine. It's typical to include a comment like this:
let list = list; // discard mut
Another way to do it (it's arguable whether it's better or not, complexity vs. readability vs. separation of concerns) is to separate the initialization.
fn peek() {
let list = {
let mut list = List::new();
list.push(1);
list
};
assert_eq!(list.peek().unwrap(),&1);
}
Your solution is correct enough. Maybe it would be a bit more readable to do it this way:
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);
}
But in your case there is another option:
fn peek(){
let list = std::iter::once(1).collect::<List<_>>();
assert_eq!(list.peek().unwrap(),&1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With