【发布时间】:2017-10-21 03:06:46
【问题描述】:
我在对象安全的基础知识上苦苦挣扎。如果我有这个代码
struct S {
x: i32,
}
trait Trait: Sized {
fn f(&self) -> i32
where
Self: Sized;
}
fn object_safety_dynamic(x: Trait) {}
我收到
error[E0038]: the trait `Trait` cannot be made into an object
--> src/lib.rs:11:29
|
5 | trait Trait: Sized {
| ----- ----- ...because it requires `Self: Sized`
| |
| this trait cannot be made into an object...
...
11 | fn object_safety_dynamic(x: Trait) {}
| ^^^^^ the trait `Trait` cannot be made into an object
当我添加或删除 : Sized 作为超级特征或 f 的绑定时,我收到的错误消息略有不同。
谁能解释一下:
-
为什么这个特定的例子不起作用? Trait Objects章节指出:
那么是什么让方法对象安全?每个方法都必须要求
Self: Sized这不是满足了吗?
-
Trait: Sized和where Self: Sized有什么区别? (嗯,是的,一个继承 trait,另一个是参数绑定,但是从 Rust 的 trait 对象角度来看? -
为了使
object_safety_dynamic起作用,我必须首选进行哪些更改?
如果重要的话,我正在使用rustc 1.19.0-nightly (01951a61a 2017-05-20)。
解决关于固定尺寸的评论。
trait TraitB {
fn f(&self) -> i32
where
Self: Sized;
fn g<T>(&self, t: T) -> i32
where
Self: Sized;
}
【问题讨论】:
标签: rust traits trait-objects