gpt4 book ai didi

rust - core::marker::Sized 未为 Foo 实现

转载 作者:行者123 更新时间:2023-11-29 07:48:09 25 4
gpt4 key购买 nike

我有这个相当简单的 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);
}

但是我得到一个编译错误:

$ 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

E0277 的错误解释似乎无关。我该如何解决这个问题?

最佳答案

当问到这个问题时,错误信息不是很清楚。相同的代码 ( Playground ) 今天显示了更好的错误消息:

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 {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

错误消息链接到 The Rust Programming Language Book,Chapter 19, section 4, "Dynamically sized types and the Sized trait" .出现问题是因为默认情况下,泛型类型参数被假定为 Sized .但是,特征对象(dyn Foo 中的Box<dyn Foo>)没有已知大小。在这种情况下这是可以接受的,因此我们修改了整体实现以允许使用未知大小的盒子:

impl<F: ?Sized> Foo for Box<F>
where F: Foo

这是固定代码,已更新到 Rust 2018 版:

trait Foo {
fn foo(&self);
}

impl Foo for () {
fn foo(&self) {
println!("hello world");
}
}

impl<F: ?Sized> Foo for Box<F>
where F: Foo
{
fn foo(&self) {
(**self).foo()
}
}

fn call_foo<F>(foo: &F)
where F: Foo
{
foo.foo()
}

fn main() {
let foo: Box<dyn Foo> = Box::new(());
call_foo(&foo);
}

关于rust - core::marker::Sized 未为 Foo 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32446485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com