【问题标题】:The best way to print a singly linked list in rust在 rust 中打印单链表的最佳方法
【发布时间】:2026-02-06 19:05:02
【问题描述】:

在我学习 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);
}

我相信这可以通过更好的方式完成,我想了解它们。除此之外,我还担心&amp;(**next) 部分。是否会创建下一个 SList 的不必要副本?

【问题讨论】:

    标签: linked-list rust singly-linked-list


    【解决方案1】:

    你的工作正常,next&amp;Box&lt;SList&gt; 类型,所以 &amp;**next&amp;SList 类型。

    但是,您可以通过取消引用模式中的框并立即获取 &amp;SList 来整理它。

    Some(box ref next) => {
        print!(" -> {}", next.n);
        l = next;
    },
    

    我还建议根据迭代器编写这样的东西。同时实现std::fmt::Show,而不是编写单独的函数。

    这是一个迭代和实现Show的示例实现:

    use std::fmt;
    
    struct SList {
        n: int,
        next: Option<Box<SList>>
    }
    
    struct SListIter<'a> {
        current: Option<&'a SList>,
    }
    
    impl SList {
        fn iter<'a>(&'a self) -> SListIter<'a> {
            SListIter {
                current: Some(self),
            }
        }
    }
    
    impl<'a> Iterator<int> for SListIter<'a> {
        fn next(&mut self) -> Option<int> {
            self.current.map(|current| {
                let value = current.n;
                self.current = match current.next {
                    Some(box ref next) => Some(next),
                    None => None
                };
                value
            })
        }
    }
    
    impl fmt::Show for SList {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            let mut first = true;
            for value in self.iter() {
                if !first {
                    try!(write!(f, " -> "));
                }
                try!(write!(f, "{}", value));
                first = false;
            }
            Ok(())
        }
    }
    
    fn main() {
        let sl1 = SList { n: 11, next: Some(box SList { n: 22, next: Some(box SList { n: 33, next: None })})};
        println!("{}", sl1);
    }
    

    【讨论】:

    • 很好的答案!感谢您这么快回复。