【发布时间】:2021-02-16 22:05:00
【问题描述】:
为什么在 trait 方法声明中允许使用大小不一的类型?例如,这段代码编译:
trait Blah {
fn blah(&self, input: [u8]) -> dyn Display;
}
但是实现Blah 是不可能的:
impl Blah for Foo {
fn blah(&self, input: [u8]) -> dyn Display {
"".to_string()
}
}
// error[E0277]: the size for values of type `(dyn std::fmt::Display + 'static)` cannot be known at compilation time
// error[E0277]: the size for values of type `[u8]` cannot be known at compilation time
给blah一个默认实现也是不可能的:
trait Blah {
fn blah(&self, input: dyn Display) -> dyn Display { "".to_string() }
}
// error[E0277]: the size for values of type `(dyn std::fmt::Display + 'static)` cannot be known at compilation time
也不允许嵌套大小不一的类型。这种不一致让我认为这是一个编译器错误:
trait Blah {
fn blah(&self, input: [str]) -> dyn Display;
}
// error[E0277]: the size for values of type `str` cannot be known at compilation time
我发现一对old GitHub issues 声称这种行为是故意的,但我找不到原因。为什么这是故意行为?如果实现这种性质的 trait 是不可能的,为什么编译器不在 trait 声明中捕获它?
【问题讨论】:
标签: rust