我已使用此递归枚举实现了我的链接列表,但现在我想为它实现自定义显示格式
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)
()
答案 0 :(得分:6)
你缺少特质限制。也就是说,您需要告诉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),
}
}
}
注意特征绑定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!
导致错误,请立即返回错误。否则,继续执行该功能。