簡體   English   中英

編寫具有關聯類型作為參數的遞歸特征方法時出錯

[英]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);
                            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

游戲圍欄鏈接-http://is.gd/xm0wvS

考慮到self.inputs()返回N其中N: Node<Output = <Self as Node>::Output> ,我印象rustc下應具有足夠的有關類型的信息input ,以滿足該呼叫到output_requested方法?

任何幫助,不勝感激!

首先:給定對象x實現Nodex.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM