Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this the Correct way to make mutable variable immutable again in rust? [duplicate]

Tags:

rust

ownership

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

    }
like image 899
Ishank Sharma Avatar asked Oct 18 '25 22:10

Ishank Sharma


2 Answers

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);
}
like image 182
NovaDenizen Avatar answered Oct 22 '25 07:10

NovaDenizen


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);
}
like image 21
Alexey Larionov Avatar answered Oct 22 '25 05:10

Alexey Larionov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!