在 Rust 中使用泛型时,“编译时无法知道 `str` 类型的值的大小”

Tia*_*Shi 4 rust

以下代码将工作并打印Foo("hello")

#[derive(Debug)]
struct Foo<'a>(&'a str);

impl<'a> From<&'a str> for Foo<'a> {
    fn from(s: &'a str) -> Self {
        Foo(s)
    }
}

fn main() {
    let s: &str = "hello";
    let foo = Foo::from(s);
    println!("{:?}", foo);
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我使用泛型,并将 all 更改strT,它将不起作用:

#[derive(Debug)]
struct Foo<'a, T>(&'a T);

impl<'a, T> From<&'a T> for Foo<'a, T> {
    fn from(s: &'a T) -> Self {
        Foo(s)
    }
}

fn main() {
    let s: &str = "hello";
    let foo = Foo::from(s);
    println!("{:?}", foo);
}
Run Code Online (Sandbox Code Playgroud)
error[E0277]: the size for values of type `str` cannot be known at compilation time
  --> a.rs:12:25
   |
2  | struct Foo<'a, T>(&'a T);
   | ------------------------- required by `Foo`
...
12 |     let foo = Foo::from(s);
   |                         ^ 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>
Run Code Online (Sandbox Code Playgroud)

&'a T等于&'a str?为什么编译器似乎使用str而不是&'a str?

bor*_*ran 5

类型参数隐含Sized在 Rust 中。您应该?Sized明确添加约束。

#[derive(Debug)]
struct Foo<'a, T: ?Sized>(&'a T);

impl<'a, T: ?Sized> From<&'a T> for Foo<'a, T> {
    fn from(s: &'a T) -> Self {
        Foo(s)
    }
}
Run Code Online (Sandbox Code Playgroud)