给出一个Box<str>
,我想为其生成一个Box<dyn _>
。具体来说:
trait StringLike {
fn length(&self) -> usize;
}
impl StringLike for str {
fn length(&self) -> usize {
self.len()
}
}
fn main() {
let x1: String = "test".to_owned();
let x2: Box<str> = x1.into_boxed_str();
let x3: Box<dyn StringLike> = x2;
}
这在x3
上给出了一个错误,指出:
error[E0277]: the size for values of type `str` cannot be known at compilation time
--> src/main.rs:15:35
|
15 | let x3: Box<dyn StringLike> = x2;
| ^^ doesn't have a size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `str`
= 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 for the cast to the object type `dyn StringLike`
第二个链接说明:
由于Rust需要了解某些细节,例如为特定类型的值分配多少空间,其类型系统的一个角落可能令人困惑:动态大小类型的概念。
我理解这一点,但是在这种情况下,我想从Box<str>
(我认为内部看起来像*str
)到Box<dyn StringLike>
(我认为内部看起来像{ {1}}),所以我看不出在编译时知道(*str, *vtable_Stringlike)
类型的概念要求。
可以进行转换吗?如果不是,是出于概念原因还是当前不可用?