I still need some explanation about rust pointer and ref:


#1

Can someone explain me please, what kind of pointer I have to use here. I am still learning rust, by implementing a List:

use std::boxed::Box;
use std::fmt::Debug;
use std::mem::replace;

#[derive(Debug)]
pub enum SList<T> {
    ListElement{e : T, next : Box<SList<T>>},
    Null
}

pub fn addToList<T>(e : T, list : SList<T>) {
    let mut iterList : SList<T> = list;
    while true {
        match iterList {
            SList::ListElement{e,next} => {
                iterList = *next;
            }
            SList::Null =>{
                iterList = SList::ListElement{e : e, next : Box::new(SList::Null)};
                break;
            }
        }
    }
}

fn main() {
    let newList : SList<i32> = SList::Null;
    for i in 0..10 {
        addToList::<i32>(i,newList);
    }
    println!("{:?}",newList);
}

#2

For what it’s worth, I’m not sure implementing a linked list in Rust is the best way to start learning the language. There is a good chance you will have to use unsafe code and advanced features. I don’t know if you’ve seen this, it should be helpful: http://cglab.ca/~abeinges/blah/too-many-lists/book/README.html

What do you mean by what kind of pointer? In the current code, you’re taking a SList by value, which means the caller will not be able to use the list after that. This is probably not what you want, instead from what you’re trying to do, I’d say you want to pass a mutable reference &mut to an SList, so you can modify it.


#3

Also, note that you don’t need to specify the type of local variables, the compiler will infer them for you. Did you try to compile this code by the way?


#4

Actually it is possible to implement a doubly linked list in safe rust:

http://cglab.ca/~abeinges/blah/too-many-lists/book/

I just want to learn all the rust references and pointers and a linked list is just perfect of this matter.