簡體   English   中英

為什么 Rust 從特征到特征分配 const 不起作用?

[英]Why does Rust assignment of const from trait to trait not work?

我正在嘗試將一個特征中定義的關聯常量分配給另一個無法按預期工作的特征。 這是一個包含 3 個特征和一個結構的最小示例:

trait A {
    const X: i32 = 1;
}

struct S;

impl A for S {}

trait B {
    const Y: i32 = A::X;
}

trait C {
    const Y: i32 = S::X;
}

fn main() {}

對應的編譯錯誤是:

error[E0283]: type annotations required: cannot resolve `_: A`
  --> src/main.rs:10:20
   |
10 |     const Y: i32 = A::X;
   |                    ^^^^
   |
note: required by `A::X`
  --> src/main.rs:2:5
   |
2  |     const X: i32 = 1;
   |     ^^^^^^^^^^^^^^^^^

E0283的解釋告訴我代碼所揭示的內容:我可以從具體類型進行分配,但不能從特征本身進行分配。 但是在E0283示例使用未定義函數的地方,我有一個已經定義的值。 為什么會這樣,如何繞過?

問題是任何實現A struct都可以為X定義自己的值。 因此,在trait B的上下文中簡單地聲明A::X並不能為編譯器提供足夠的信息,說明應該選擇A哪個impl

如果您希望impl B東西也impl A ,您可以嘗試以下操作(我手頭沒有編譯器,但想法應該很清楚):

trait B : A {
    const Y: i32 = <Self as A>::X;
}

Traits 應該由一個具體的類型來實現,而不應該自己定義一個不能在實現者中改變的常量。 您指定的是默認值,而不是所有實現者必須遵守的值。 如果所有類型都必須具有相同的X值,則不需要特征。

因此A::X不是一個明確定義的值。

這是一個說明原因的示例:

trait A {
    const X: i32 = 1;
}

struct S;

impl A for S {}

struct R;

impl A for R {
    const X: i32 = 42;
}

fn main() {
    println!("S: {}", S::X);
    println!("R: {}", R::X);
    println!("S: {}", <S as A>::X); // A::X alone is ambiguous
    println!("R: {}", <R as A>::X);
}

(鏈接到游樂場)

您正在做的類似於嘗試在特征上調用默認函數,這里是錯誤 E0283:

trait A {
    fn get_x() -> i32 {
        1
    }
}

struct S;

impl A for S {}

struct R;

impl A for R {
    fn get_x() -> i32 {
        42
    }
}

fn main() {
    // A::get_x() is ambiguous but there are not:
    println!("S: {}", S::get_x());
    println!("R: {}", R::get_x());
    println!("S: {}", <S as A>::get_x());
    println!("R: {}", <R as A>::get_x());
}

(鏈接到游樂場)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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