gpt4 book ai didi

linked-list - 在 Rust 中打印单向链表的最佳方式

转载 作者:行者123 更新时间:2023-11-29 08:06:57 25 4
gpt4 key购买 nike

在我学习 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 的不必要副本?

最佳答案

你所拥有的工作正常,next类型 &Box<SList> ,等等 &**next类型为 &SList .

但是,您可以通过取消引用模式中的框并获得 &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);
}

关于linked-list - 在 Rust 中打印单向链表的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24196100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com