< 返回版块

humphrycc 发表于 2020-04-13 00:39

Tags:trait, trait object, self, default implementation

请教一下如何在trait的fn中将self作为trait object?

代码如下

trait A {
    fn plus(&self) -> &dyn A {
        self
    }
}

错误:

error[E0277]: the size for values of type `Self` cannot be known at compilation time
 --> src/lib.rs:3:9
  |
2 |     fn plus(&self) -> &dyn A {
  |                             - help: consider further restricting `Self`: `where Self: std::marker::Sized`
3 |         self
  |         ^^^^ doesn't have a size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `Self`
  = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
  = note: required for the cast to the object type `dyn A`

playground

评论区

写评论
Mike Tang 2020-04-26 10:38

谢谢提供!刷赞。

作者 humphrycc 2020-04-26 07:46

自问自答,具体答案Stackoverflow的一个问题

简单来说,在RFC 546里,Self?Sized的。

1 共 2 条评论, 1 页