說實話,我很難用語言來描述這個問題,所以我馬上展示代碼:
// SomeType / SomeTrait
struct SomeType;
trait SomeTrait {
fn do_sth() -> &'static str;
}
impl SomeTrait for SomeType {
fn do_sth() -> &'static str {
"do_sth()"
}
}
// SomeOtherType / SomeOtherTrait
struct SomeOtherType;
impl SomeOtherType {
fn get_some_trait<C>(&self, c: C)
where
C: Fn(SomeType), // Takes clousure, clousure have to get `SomeType`-type paramm
{
c(SomeType);
}
}
trait SomeOtherTrait {
fn perform_sth<C, D>(&self, c: C)
where
D: SomeTrait,
C: Fn(&D) -> &'static str; // Takes clousure, clousure have to get type that implements SomeTrait
}
impl SomeOtherTrait for SomeOtherType {
fn perform_sth<C, D>(&self, c: C)
where
D: SomeTrait,
C: Fn(&D) -> &'static str,
{
self.get_some_trait(|arg: SomeType| {
c(&arg); // <- Problem
// Error: expected type parameter `D`, found struct `SomeType`
// But `D: SomeTrait` and SomeType implements `SomeTrait`
});
}
}
fn main() {}
上面的代碼是我發現自己所處情況的簡化模型。
如果我有|arg: SomeType|,則cclosure 參考泛型型別T,它實作了SomeType- 為什么我不能arg作為引數傳遞c?
預先感謝您幫助解決問題。我為我的英語中的任何錯誤道歉。
uj5u.com熱心網友回復:
我認為您當前的定義SomeOtherTrait不允許這樣做,因為它D通過定義 on將引數填充給呼叫者,perform_sth但您在內部已經SomeType通過SomeOtherType::get_some_trait.
如果你介紹一個泛型引數D上SomeOtherTrait,可以系結D在一個給定型別的實施SomeOtherTrait到任何它需要:
trait SomeOtherTrait<D> {
fn perform_sth<C>(&self, c: C)
where
D: SomeTrait,
C: Fn(&D) -> &'static str; // Takes clousure, clousure have to get type that implements SomeTrait
}
impl SomeOtherTrait<SomeType> for SomeOtherType {
fn perform_sth<C>(&self, c: C)
where
C: Fn(&SomeType) -> &'static str,
{
self.get_some_trait(|arg| {
c(&arg);
});
}
}
另一個選項是調整get_some_trait為通用引數到c,盡管您隨后需要能夠構造它,例如通過D::Default():
// ...
struct SomeOtherType;
impl SomeOtherType {
fn get_some_trait<C, D>(&self, c: C)
where
D: Default,
C: Fn(D), // Takes clousure, clousure have to get `SomeType`-type paramm
{
c(D::default());
}
}
// ...
這反過來又需要將D: Default系結添加到SomeOtherTrait::perform_sth。
uj5u.com熱心網友回復:
問題是這只有在Dis時才有效SomeType。比如說我有下面的代碼:
struct Foo;
impl SomeTrait for Foo {
fn do_sth() -> &'static str {
"Foo"
}
}
SomeOtherType.perform_sth::<_, Foo>(|_: &Foo| "Bla" );
這段代碼是完全有效的,但是應該perform_sth使用SomeType盡管我的閉包期望嘗試使用的當前實作Foo。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/366529.html
上一篇:理解泛型以及如何
