在努力学习Rust的过程中,我正在尝试找到在Rust中打印单向链表结构的最佳方法。以下是我编写的代码:
struct SList {
n: int,
next: Option<Box<SList>>
}
fn print_slist(mut l: &SList) {
print!("{}", l.n);
loop {
match l.next {
Some(ref next) => { print!(" -> {}", next.n); l = &(**next); },
None => { break; }
}
}
println!("");
}
fn main() {
let sl1 = SList { n: 11, next: Some(box SList { n: 22, next: Some(box SList { n: 33, next: None })})};
print_slist(&sl1);
}
我相信有更好的方法可以完成这个操作,我希望能够了解它们。除此之外,我还关心
&(**next)
部分。它是否会创建一个不必要的SList
副本?