3

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);

    }
Ishank Sharma
  • 79
  • 1
  • 7

2 Answers2

4

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);
}
NovaDenizen
  • 5,089
  • 14
  • 28
2

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);
}
Alexey S. Larionov
  • 6,555
  • 1
  • 18
  • 37