在方法中使用特征和泛型的 Rust 语法是什么?



通常,我想要一个特性(Requestor(,它包含一个方法,在另一个特性中返回T(ResponseWriter(。

我在谷歌上搜索了一下,试图找到这些文件,但我找不到适合我情况的语法。编译器说:

T: ResponseWriter;
|                ^^^^^^^^^^^^^^ expected 1 type argument

但是,我不能写T: ResponseWriter<U>,它会给我带来其他错误。

所以我的问题是正确的语法是什么?

pub trait ResponseWriter<T> {
fn get_result(&self) -> T;
}
pub trait Requestor {
fn process<T>(&self) -> T
where
T: ResponseWriter;
}
pub struct Request {
pub x: String,
}
impl Requestor for Request {
fn process<T>(&self) -> T {
Response {
res: format!("{} {}", self.x, "world".to_owned()),
}
}
}
pub struct Response<T> {
pub res: T,
}
impl<T> ResponseWriter<T> for Response<T> {
fn get_result(&self) -> T {
self.res
}
}
let request = Request {
x: "hello".to_owned(),
};
println!("{}", request.process().get_result());

相关类型可以重写代码。它完美地解决了这个问题并简化了代码。

pub trait Requestor {
type Output;
fn process(&self) -> Self::Output;
}
pub struct Request {
pub x: String,
}
impl Requestor for Request {
type Output = String;
fn process(&self) -> String {
format!("{} {}", self.x, "world".to_owned())
}
}
let request = Request {
x: "hello".to_owned(),
};
println!("{}", request.process());

最新更新