Tha*_*you 3 formatting enums rust
我使用这个递归枚举实现了我的链表,但现在我想为它实现一个自定义显示格式
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),
}
}
}
Run Code Online (Sandbox Code Playgroud)
错误
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`
Run Code Online (Sandbox Code Playgroud)
如果重要的话,这是我的其余代码
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);
}
Run Code Online (Sandbox Code Playgroud)
预期产出
(1 (2 (3 ())))
3
(1 (4 (9 ())))
()
Run Code Online (Sandbox Code Playgroud)
真的,我想看到这个,但我完全不知道如何使用这种输出fmt::Result
(1 2 3)
3
(1 4 9)
()
Run Code Online (Sandbox Code Playgroud)
你错过了一个特质限制.也就是说,你需要告诉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),
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意特征限制T: fmt::Display.这基本上意味着:if Timplements 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, ")")
}
Run Code Online (Sandbox Code Playgroud)
请注意?最多的write!宏调用.它基本上意味着:如果这write!导致错误,现在返回错误.否则,继续执行该功能.