gpt4 book ai didi

generics - 又是 : "expected type parameter, found struct"

转载 作者:行者123 更新时间:2023-11-29 08:02:54 25 4
gpt4 key购买 nike

<分区>

关于这个特定的错误消息,已经有几个问题。我阅读了所有这些内容,但我无法弄清楚我在这里面临的确切问题是什么,也不知道如何解决它。

我有一个 struct 对传入的参数有要求,我想提供一些方便的函数来构造一个新实例。来了:

use std::io::{Cursor, Read, Seek};

pub struct S<R: Read + Seek> {
p: R,
}

impl<R: Read + Seek> S<R> {
pub fn new(p: R) -> Self {
S { p }
}

pub fn from_string(s: String) -> Self {
S::new(Cursor::new(s))
}
}

上面的最小示例给出了以下错误:

error[E0308]: mismatched types
--> src/main.rs:13:16
|
13 | S::new(Cursor::new(s))
| ^^^^^^^^^^^^^^ expected type parameter, found struct `std::io::Cursor`
|
= note: expected type `R`
found type `std::io::Cursor<std::string::String>`
= help: here are some functions which might fulfill your needs:
- .into_inner()

我尝试了很多变体,但我总是以同样的错误告终。另请注意,从其他地方(例如 main)使用游标调用 S::new 会按预期工作。我知道它与泛型有关,等等(从对其他类似问题的回答)但是:我如何在 impl< 中提供这样的 from_* 方法 我的 struct?

25 4 0