我已经使用这个递归枚举实现了我的链表,但现在我想为它实现一个自定义显示格式
use std::fmt;
#[derive(Debug)]
enum List<A> {
Empty,
Cons(A, Box<List<A>>),
}
impl<T> fmt::Display for List<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
List::Empty => write!(f, "()"),
List::Cons(x, ref xs) => write!(f, "({} {})", x, xs),
}
}
}
错误
error[E0277]: the trait bound `T: std::fmt::Display` is not satisfied
--> src/main.rs:13:59
|
13 | List::Cons(x, ref xs) => write!(f, "({} {})", x, xs),
| ^ the trait `std::fmt::Display` is not implemented for `T`
|
= help: consider adding a `where T: std::fmt::Display` bound
= note: required by `std::fmt::Display::fmt`
如果重要的话,这是我的其余代码
fn cons<A>(x: A, xs: List<A>) -> List<A> {
return List::Cons(x, Box::new(xs));
}
fn len<A>(xs: &List<A>) -> i32 {
match *xs {
List::Empty => 0,
List::Cons(_, ref xs) => 1 + len(xs),
}
}
fn map<A, B>(f: &Fn(&A) -> B, xs: &List<A>) -> List<B> {
match *xs {
List::Empty => List::Empty,
List::Cons(ref x, ref xs) => cons(f(x), map(f, xs)),
}
}
fn main() {
let xs = cons(1, cons(2, cons(3, List::Empty)));
println!("{}", xs);
println!("{:?}", len(&xs));
let f = |x: &i32| (*x) * (*x);
let ys = map(&f, &xs);
println!("{}", ys);
println!("{}", List::Empty);
}
预期输出
(1 (2 (3 ())))
3
(1 (4 (9 ())))
()
真的我想看到这个,但我完全不知道我将如何使用 fmt::Result
(1 2 3)
3
(1 4 9)
()
最佳答案
解决编译错误
您缺少一个特征界限。也就是说,你需要告诉 Rust T
可以显示:
impl<T: fmt::Display> fmt::Display for List<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
List::Empty => write!(f, "()"),
List::Cons(ref x, ref xs) => write!(f, "({} {})", x, xs),
}
}
}
注意 trait bound T: fmt::Display
.这基本上意味着:如果 T
工具 fmt::Display
, 然后 List<T>
工具 fmt::Display
锦上添花
我不确定您是否可以使用递归定义获得良好的格式。此外,Rust 不保证尾调用优化,因此始终存在堆栈溢出的可能性。
另一种定义可以是:
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "(")?;
let mut temp = self;
while let List::Cons(ref x, ref xs) = *temp {
write!(f, "{}", x)?;
// Print trailing whitespace if there are more elements
if let List::Cons(_, _) = **xs {
write!(f, " ")?;
}
temp = xs;
}
write!(f, ")")
}
注意 ?
大多数write!
宏调用。它基本上意味着:如果这个write!
导致错误,立即返回错误。否则,继续执行函数。
关于enums - 如何在 Rust 中的通用类型枚举上实现 fmt::Display?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43113790/