2017-09-25 35 views
7

以下鏽病代碼無法編譯:爲什麼`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 
    } 
} 

爲什麼在這種情況下不能使用SelfSelf哪裏可以使用*?還有什麼我可以用來避免在方法體中重複類型名稱?

*我忽略了性狀的使用,其中Self指任何類型實現的特質。

+0

枚舉有點奇怪,因爲它們作用於類型和名稱空間之間。在這種情況下,Foo更像是一個名稱空間。這就是說,這只是好奇心,還是這阻止你做你想做的事情? –

+0

@PaoloFalabella這裏'Self'的常用用法是減少類型名稱的重複。我只是希望我能在方法體中做同樣的事情。 – Challenger5

+0

我遇到了一些很好的文章,https://users.rust-lang.org/t/confused-by-use-of-self-in-example-in-chapter-17-of-rust-book-2nd-編輯/ 11394。希望它對你有所幫助。 – shri

回答

0

枚舉建設者!=關聯的項目。

這是一個已知的issue,但預計不會被固定,至少在可預見的將來不會。從我所收集到的信息來看,這並不是微不足道的,在這一點上,相關文檔或錯誤信息更有可能得到改善。

關於相關項目一般;雖然,Rust書上有一章associated types。另外,關於Selfthis related question有很多很好的答案。

1

如果枚舉名Foo在現實中是長,要避免在執行重複它,你有兩個選擇:

  • use LongEnumName as Short在模塊級。這將允許您在f的末尾返回Short::Bar
  • use LongEnumName::*在模塊級別,允許更短的Bar

如果您省略pub,則導入將是內部的,並且不會影響模塊的公共API。

1

重要的是要注意的是,錯誤說相關的項目。 enum Foo { Baz }沒有關聯的項目。的性狀可以有相關的項目:

trait FooBaz { type Baz } 
//    ^~~~~~~~ - associated item 

總結:

爲什麼不能Self在這種情況下使用?

由於this issue

Self似乎充當類型別名,儘管進行了一些修改。

0123哪裏可以使用Self

自我只能用於性狀和impl s。此代碼:

struct X { 
    f: i32, 
    x: &Self, 
} 

輸出如下:

error[E0411]: cannot find type `Self` in this scope 
--> src/main.rs:3:9 
    | 
3 |  x: &Self, 
    |   ^^^^ `Self` is only available in traits and impls 

這可能是一個暫時的情況,並在未來可能會改變!

更準確地說,應Self只用作(例如fn self_in_self_out(&self) -> Self)或訪問相關聯的類型的方法簽名的一部分:

enum Foo { 
    Baz, 
} 

trait FooBaz { 
    type Baz; 

    fn b(&self) -> Self::Baz; // Valid use of `Self` as method argument and method output 
} 


impl FooBaz for Foo { 
    type Baz = Foo; 

    fn b(&self) -> Self::Baz { 
     let x = Foo::Baz as Self::Baz; // You can use associated type, but it's just a type 
     x 
    } 
} 

我認爲user4815162342 covered the rest of the answer best

相關問題