此函数编译:
fn edit<S: AsRef<str>>(w: S) {}
如果我键入通用参数别名:
type Word = dyn AsRef<str>;
fn edit(w: Word) {}
我收到一个错误:
error[E0277]: the size for values of type `(dyn std::convert::AsRef<str> + 'static)` cannot be known at compilation time
--> src/lib.rs:3:9
|
3 | fn edit(w: Word) {}
| ^ doesn't have a size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `(dyn std::convert::AsRef<str> + 'static)`
= note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
= note: all local variables must have a statically known size
= help: unsized locals are gated as an unstable feature
为什么会这样?
所有函数在编译时都需要知道其参数的大小。但是,您正在使用w
,其大小无法在编译时确定。为了能够执行动态调度,您需要使用特征对象。您可以通过两种方式完成此操作。