【问题标题】:Why is the trait `core::fmt::Show` not implemented for the type `core::fmt::Show + Sized`?为什么没有为`core::fmt::Show + Sized`类型实现特征`core::fmt::Show`?
【发布时间】:2015-05-24 10:04:27
【问题描述】:

我正在尝试编译一些代码,但遇到了一个非常奇怪的错误:

特征 core::fmt::Show 没有为 core::fmt::Show + Sized 类型实现

还有代码:

use std::fmt::Show;

fn main() {
    println!("{}", return_showed()); // Error occurs here
}

fn return_showed() -> Box<Show+Sized+'static> {
    box "test" as Box<Show+Sized>
}

这对我来说没有多大意义。这是编译器的错误吗?

提前致谢!

【问题讨论】:

  • 你能补充一点你为什么需要+Sized吗?
  • @Shepmaster 在我的实际代码中,我需要一个 Sized。这只是一个简化的测试用例。

标签: rust


【解决方案1】:

Rust 1.0

原始问题中发布的代码现在可以按预期编译。

原创

如果你不需要Sized,那么你可以使用这个:

fn show_boxed() -> Box<Show+'static> { // '
    box "test"
}

fn main() {
    println!("{}", &*show_boxed());
}

据我了解,&amp;* 将取消引用然后重新引用 Box。这会将其从 Box&lt;core::fmt::Show&gt; 更改为 &amp;core::fmt::Show,格式化机制知道如何处理。

编辑

你也可以只选择你想要的特征对象:

fn return_showed() -> Box<Show+Sized+'static> { // '
    box "test" as Box<Show+Sized>
}

fn main() {
    let z: &Show = &*return_showed();
    println!("{}", z);
}

我同意这不太理想;可能值得提交一个 Rust 问题。

【讨论】:

  • 我仍然想知道是什么导致了这个错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-06
  • 1970-01-01
  • 2015-08-08
  • 1970-01-01
相关资源
最近更新 更多