Rust是否有办法使用默认的关联类型?
以下是我添加的关联类型,以便可以从我的trait方法返回futures:Rust是否有办法使用默认的关联类型?,rust,Rust,以下是我添加的关联类型,以便可以从我的trait方法返回futures: pub trait RtspClient: Runnable { type PlayResult: Future<Output = std::result::Result<(), ()>>; type ConnectResult: Future<Output = std::result::Result<(), RtspConnectionError>>;
pub trait RtspClient: Runnable {
type PlayResult: Future<Output = std::result::Result<(), ()>>;
type ConnectResult: Future<Output = std::result::Result<(), RtspConnectionError>>;
type DisconnectResult: Future<Output = std::result::Result<(), RtspDisconnectionError>>;
fn connect(&self) -> RtspClient::ConnectResult {
Ok(())
}
fn disconnect(&self) -> RtspClient::DisconnectResult {
Ok(())
}
}
有没有办法强迫rust使用我在特质定义中已经写过的默认值?这里有很多误解。关联类型的未来部分不是默认值,而是约束。未来不是一种类型,而是一种特质。例如,它说实现的结果必须满足未来的约束 默认关联类型如下所示:
pub trait RtspClient {
type PlayResult = Ready<Result<(), ()>>; // using std::future::Ready as an example
}
即使它真的起作用了,你也很难把它作为特质对象来使用。每个实现可以有不同的具体关联类型,但是您需要指定具体关联类型以将其用作trait对象。毫无疑问,它们将不匹配:
struct MyDefaultClient;
impl RtspClient for MyDefaultClient {
// just uses the default types
fn connect(&self) -> Self::ConnectResult {
ready(Ok(()))
}
fn disconnect(&self) -> Self::DisconnectResult {
ready(Ok(()))
}
}
struct MyCustomClient;
impl RtspClient for MyCustomClient {
type ConnectResult = Pending<Result<(), RtspConnectionError>>; // different associated types
type DisconnectResult = Pending<Result<(), RtspDisconnectionError>>;
fn connect(&self) -> Self::ConnectResult {
pending()
}
fn disconnect(&self) -> Self::DisconnectResult {
pending()
}
}
fn main() {
let data = [
Box::new(MyDefaultClient) as Box<dyn RtspClient<ConnectResult = _, DisconnectResult = _>>,
Box::new(MyCustomClient),
];
}
关联的类型和特征对象不会以这种方式混合。您可以将它们视为常规泛型类型:Struct与Struct是完全不同的类型
如果您想交替使用不同的实现,您应该遵循链接答案中的其他建议,使用盒装期货、Pin或helper板条箱异步特性,而不是使用关联类型。这里有很多误解。关联类型的未来部分不是默认值,而是约束。未来不是一种类型,而是一种特质。例如,它说实现的结果必须满足未来的约束 默认关联类型如下所示:
pub trait RtspClient {
type PlayResult = Ready<Result<(), ()>>; // using std::future::Ready as an example
}
即使它真的起作用了,你也很难把它作为特质对象来使用。每个实现可以有不同的具体关联类型,但是您需要指定具体关联类型以将其用作trait对象。毫无疑问,它们将不匹配:
struct MyDefaultClient;
impl RtspClient for MyDefaultClient {
// just uses the default types
fn connect(&self) -> Self::ConnectResult {
ready(Ok(()))
}
fn disconnect(&self) -> Self::DisconnectResult {
ready(Ok(()))
}
}
struct MyCustomClient;
impl RtspClient for MyCustomClient {
type ConnectResult = Pending<Result<(), RtspConnectionError>>; // different associated types
type DisconnectResult = Pending<Result<(), RtspDisconnectionError>>;
fn connect(&self) -> Self::ConnectResult {
pending()
}
fn disconnect(&self) -> Self::DisconnectResult {
pending()
}
}
fn main() {
let data = [
Box::new(MyDefaultClient) as Box<dyn RtspClient<ConnectResult = _, DisconnectResult = _>>,
Box::new(MyCustomClient),
];
}
关联的类型和特征对象不会以这种方式混合。您可以将它们视为常规泛型类型:Struct与Struct是完全不同的类型
如果您想互换地使用不同的实现,那么您应该遵循链接答案中的其他建议,使用boxed futures、Pin或helper claret async trait,而不是使用关联的类型