我有这个相当简单的Rust程序:
use std::ops::Deref;
trait Foo {
fn foo(&self);
}
impl Foo for () {
fn foo(&self) {
println!("hello world");
}
}
impl<F> Foo for Box<F> where F: Foo {
fn foo(&self) {
let f: &F = self.deref();
f.foo()
}
}
fn call_foo<F>(foo: &F) where F: Foo {
foo.foo()
}
fn main() {
let foo: Box<Foo> = Box::new(());
call_foo(&foo);
}
Run Code Online (Sandbox Code Playgroud)
但是我收到了编译错误:
$ rustc main.rs
main.rs:26:3: 26:11 error: the trait `core::marker::Sized` is not implemented for the type `Foo` [E0277]
main.rs:26 call_foo(&foo);
^~~~~~~~
main.rs:26:3: 26:11 help: run `rustc --explain E0277` to see a detailed explanation
main.rs:26:3: 26:11 note: `Foo` does not have a constant size known at compile-time
main.rs:26 call_foo(&foo);
^~~~~~~~
main.rs:26:3: 26:11 note: required by `call_foo`
main.rs:26 call_foo(&foo);
^~~~~~~~
error: aborting due to previous error
Run Code Online (Sandbox Code Playgroud)
E0277的错误解释似乎无关.我该如何解决?
这是一个棘手的问题,因为错误消息不是很好.这是固定代码:
error[E0277]: the size for values of type `dyn Foo` cannot be known at compilation time
--> src/main.rs:26:3
|
26 | call_foo(&foo);
| ^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `dyn Foo`
= 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 because of the requirements on the impl of `Foo` for `std::boxed::Box<dyn Foo>`
note: required by `call_foo`
--> src/main.rs:20:1
|
20 | fn call_foo<F>(foo: &F) where F: Foo {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
出现问题是因为默认情况下,假定泛型类型参数Sized.但是,特征对象(Sizedin dyn Foo)没有已知的大小.在这种情况下,这是可以接受的,因此我们修改了一揽子实现,以允许包含未知大小的框:
impl<F: ?Sized> Foo for Box<F>
where F: Foo
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1824 次 |
| 最近记录: |