【发布时间】:2015-06-05 06:50:11
【问题描述】:
更新:这个更简单的代码 (play) 表现出相同的症状:
use std::fmt::Display;
pub fn arg(a: &str, b: &Display) {
}
fn main() {
arg("foo", "bar");
}
给出错误:
<anon>:7:16: 7:21 error: the trait `core::marker::Sized` is not implemented for the type `str` [E0277]
<anon>:7 arg("foo", "bar");
^~~~~
<anon>:7:16: 7:21 note: `str` does not have a constant size known at compile-time
<anon>:7 arg("foo", "bar");
^~~~~
但我认为这里没有任何理由要求尺寸。 a 和b 处理相同,属于同一类型,a 没有问题。所以
- 为什么
b有问题,以及 - 我如何告诉它 Trait 的大小不应该是已知的。
事实上,它是一个 trait 类型,无论底层类型是什么,它都不知道类型。那么它为什么要大小呢?
哦,我不应该忘记:在实际用例中,我需要动态多态性。该函数(方法)将与不同实际类型的参数和存储的引用链接(参见下面的原始展示),所以我无法将其转换为T: Trait + ?Sized。
原始展览:
我有一些类似以下的代码 (see also on play.rust-lang.org):
pub trait Trait { /* some methods */ }
impl Trait for str { /* some implementation */ }
pub struct Struct<'a> {
args: HashMap<&'a str, &'a Trait>,
}
impl<'a> Struct<'a> {
pub fn new() -> Self {
Struct { args: HashMap::new() }
}
pub fn arg(mut self, key: &'a str, value: &'a Trait) -> Struct<'a> {
self.args.insert(key, value);
return self;
}
// of course there is something to process the collected arguments too
}
fn main() {
Struct::new().arg("foo", "bar");
}
这给了我错误:
test.rs:32:30: 32:35 error: the trait `core::marker::Sized` is not implemented for the type `str` [E0277]
test.rs:32 Struct::new().arg("foo", "bar");
^~~~~
test.rs:32:30: 32:35 note: `str` does not have a constant size known at compile-time
test.rs:32 Struct::new().arg("foo", "bar");
【问题讨论】:
标签: compiler-errors rust traits