[英]Error when writing a recursive trait method with an associated type as an argument
我一直在更新庫以使用Rust的新關聯類型。 該庫提供了用於構造DSP圖的Node
特征。 以下是特征的簡化版本,它會產生與我在庫中遇到的錯誤相同的錯誤。
use std::default::Default;
use std::num::Float;
trait Node {
type Output: Default + Float;
fn inputs<N>(&mut self) -> Vec<&mut N>
where
N: Node<Output = <Self as Node>::Output>;
fn output_requested(&mut self, output: &mut <Self as Node>::Output) {
for input in self.inputs().into_iter() {
let mut working: <Self as Node>::Output = Default::default();
input.output_requested(&mut working);
// ^~~~~ ERROR
*output = *output + working;
}
}
}
fn main() {}
這是錯誤消息
<anon>:15:19: 15:49 error: the type of this value must be known in this context
<anon>:15 input.output_requested(&mut working);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
考慮到self.inputs()
返回N
其中N: Node<Output = <Self as Node>::Output>
,我印象rustc下應具有足夠的有關類型的信息input
,以滿足該呼叫到output_requested
方法?
任何幫助,不勝感激!
首先:給定對象x
實現Node
, x.inputs()
接受通用參數N
並返回Vec<&mut N>
。
現在,讓我們寫出output_requested
發生的事情的更明確類型的版本。
(順便說一句,有了for
循環的新IntoIterator
基礎,不再需要.into_iter()
。)
fn output_requested(&mut self, output: &mut <Self as Node>::Output) {
let inputs: Vec<&mut N> = self.inputs();
for input in inputs { // input: &mut N
let mut working: <Self as Node>::Output = Default::default();
input.output_requested(&mut working);
*output = *output + working;
}
}
好吧; 我們對N
型有什么看法? 我們可以解決嗎?
它來自self.inputs()
,引入了它實現Node<Output = <Self as Node>::Output>
的約束;
在對象上,您調用了方法self.output_requested(&mut <Self as Node>::Output)
,該方法僅確認上一點。
因此,我們對N
所有了解就是它以與我們的類型相同的Output
實現Node
。 但這可能是兩種完全不同的類型,如下所示:
impl Node for A {
type Output = Out;
…
}
impl Node for B {
type Output = Out;
…
}
因此,您可以看到無法確定N
是多少。 它始終可以是Self
,但也可能存在其他可能性,因此不能靜態解決,因此是被禁止的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.