Core :: marker :: Size not implemented for Foo

I have a pretty simple Rust program:

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); } 

But I get compilation errors:

 $ 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 

The explanation of the error for E0277 seems unrelated. How to fix it?

+6
source share
1 answer

This is a complex issue because the error message is not stellar. Here's the fixed code:

 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<Foo> = Box::new(()); call_foo(&foo); } 

The problem arises because by default the generic parameter is considered Sized . However, the feature object ( Foo in Box<Foo> ) does not have a known size. This is acceptable in this case, so we modify the shell implementation to allow things with an unknown size:

 impl<F: ?Sized> Foo for Box<F> where F: Foo 
+6
source

All Articles