如何将通用T转换为String?

时间:2019-04-01 18:46:20

标签: rust

我正在尝试打印自定义类型:

struct Node<T> {
    prev: Option<Box<Node<T>>>,
    element: T,
    next: Option<Box<Node<T>>>,
}

现在,问题所在:

print!(
    "{0} -> {1}",
    String::from(node.element),
    String::from(node.next)
);
error[E0277]: the trait bound `std::string::String: std::convert::From<T>` is not satisfied
  --> src/lib.rs:10:9
   |
10 |         String::from(node.element),
   |         ^^^^^^^^^^^^ the trait `std::convert::From<T>` is not implemented for `std::string::String`
   |
   = help: consider adding a `where std::string::String: std::convert::From<T>` bound
   = note: required by `std::convert::From::from`

error[E0277]: the trait bound `std::string::String: std::convert::From<std::option::Option<std::boxed::Box<Node<T>>>>` is not satisfied
  --> src/lib.rs:11:9
   |
11 |         String::from(node.next)
   |         ^^^^^^^^^^^^ the trait `std::convert::From<std::option::Option<std::boxed::Box<Node<T>>>>` is not implemented for `std::string::String`
   |
   = help: the following implementations were found:
             <std::string::String as std::convert::From<&'a str>>
             <std::string::String as std::convert::From<std::borrow::Cow<'a, str>>>
             <std::string::String as std::convert::From<std::boxed::Box<str>>>
   = note: required by `std::convert::From::from`

如何将node.element投射到String并将Option<Box<Node<T>>>投射到String

1 个答案:

答案 0 :(得分:3)

编译器告诉您:

  

考虑添加一个where std::string::String: std::convert::From<T>绑定

fn example<T>(node: Node<T>)
where
    String: From<T>,
{
    // ...
}

这对于String: From<Option<Node<T>>>不起作用,因为没有这样的实现。


如果您想格式化您的结构,则需要使用Display的实现。没有理由仅仅为了显示它而将值转换为String

fn example<T>(node: Node<T>)
where
    T: std::fmt::Display
{
    // ...
}

同样,这在较大的情况下不起作用,因为Node<T>Option<T>都没有实现Display

另请参阅:

您可能想要类似的东西

fn example<T>(mut node: Node<T>)
where
    T: std::fmt::Display,
{
    print!("{}", node.element);
    while let Some(n) = node.next {
        print!(" -> {}", n.element);
        node = *n;
    }
}

fn example<T>(mut node: &Node<T>)
where
    T: std::fmt::Display,
{
    print!("{}", node.element);
    while let Some(n) = &node.next {
        print!(" -> {}", n.element);
        node = &n;
    }
}

甚至可以自己使用相同的代码来实现Display / Debug

您还应该阅读Learning Rust With Entirely Too Many Linked Lists。您正在尝试创建一个双向链接列表,这在安全的Rust中是不可能的。