以下鏽病代碼無法編譯:爲什麼`Self`不能用於引用方法體中的枚舉變體?
enum Foo {
Bar,
}
impl Foo {
fn f() -> Self {
Self::Bar
}
}
錯誤信息混淆了我:
error[E0599]: no associated item named `Bar` found for type `Foo` in the current scope
--> src/main.rs:7:9
|
7 | Self::Bar
| ^^^^^^^^^
這個問題可以通過使用Foo
代替Self
是固定的,但給我的印象,因爲Self
奇怪應該指的是正在實施的類型(忽略特徵),在這種情況下是Foo
。
enum Foo {
Bar,
}
impl Foo {
fn f() -> Self {
Foo::Bar
}
}
爲什麼在這種情況下不能使用Self
? Self
哪裏可以使用*?還有什麼我可以用來避免在方法體中重複類型名稱?
*我忽略了性狀的使用,其中Self
指任何類型實現的特質。
枚舉有點奇怪,因爲它們作用於類型和名稱空間之間。在這種情況下,Foo更像是一個名稱空間。這就是說,這只是好奇心,還是這阻止你做你想做的事情? –
@PaoloFalabella這裏'Self'的常用用法是減少類型名稱的重複。我只是希望我能在方法體中做同樣的事情。 – Challenger5
我遇到了一些很好的文章,https://users.rust-lang.org/t/confused-by-use-of-self-in-example-in-chapter-17-of-rust-book-2nd-編輯/ 11394。希望它對你有所幫助。 – shri