如何将泛型T转换为String?

问题描述 投票:-2回答:1

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

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`

如何将qazxsw poi施放到qazxsw poi和qazxsw poi到qazxsw poi?

rust
1个回答
3
投票

正如编译器告诉你的那样:

考虑添加node.element绑定

String

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


如果要格式化结构,则需要实现String。为了显示它,没有理由将值转换为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

甚至可以使用相同的代码自己实现Should I implement Display or ToString to render a type as a string? / The trait bound `T: std::fmt::Display` is not satisfied

您还应该阅读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; } } 。您正在尝试创建一个双链表,这在安全的Rust中是不可能的。

© www.soinside.com 2019 - 2024. All rights reserved.