2015-06-21 63 views
1

看來我不能把同一結構的方法生鏽或也許我不明白的地方的IMPL方法:調用從另一個IMPL方法

struct St1 { 
    aa: String 
} 

impl St1 { 
    pub fn method1() -> String { 
    //.... 
    method2() //error: unresolved name method2 
    } 

    pub fn method2() -> String { 
    //.... 
    } 
} 

這是它是如何應該是什麼?

回答

3

您需要完全限定您所調​​用的方法。

struct St1 { 
    aa: String 
} 

impl St1 { 
    pub fn method1() -> String { 
     St1::method2() 
    } 

    pub fn method2() -> String { 
     unimplemented!() 
    } 
} 

上關的機會,你的意思是,這些方法是實例方法,那麼你還必須完全限定它們,但使用self代替:

struct St1 { 
    aa: String 
} 

impl St1 { 
    pub fn method1(&self) -> String { 
     self.method2() 
    } 

    pub fn method2(&self) -> String { 
     unimplemented!() 
    } 
} 

注意防鏽風格爲4-空間縮進。

+0

1)如何訪問'aa'? 2)使用Impl是一種推薦的風格,還是使用「純」功能而不將其包裝到Impl中更好? –

+3

@jawanam(1)是另一個問題,應單獨詢問。它也包含在[* The Rust Programming Language *](http://doc.rust-lang.org/book/)中,你應該**閱讀。 (2)是「它取決於」。你的函數與結構高度相關嗎?如果是這樣,我會使用'impl'。 – Shepmaster

+0

具體爲[方法語法](http://doc.rust-lang.org/book/method-syntax.html)。 – Shepmaster