![](/img/trans.png)
[英]Why does Rust "From" trait implementation give lifetime error, but custom trait does not?
[英]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.