2016-06-17 32 views
1

我試圖應用一些面向對象,但我面臨一個問題。找不到方法/字段名稱

use std::io::Read; 

struct Source { 
    look: char 
} 

impl Source { 
    fn new() { 
     Source {look: '\0'}; 
    } 

    fn get_char(&mut self) { 
     self.look = 'a'; 
    } 
} 


fn main() { 
    let src = Source::new(); 
    src.get_char(); 

    println!("{}", src.look); 
} 

編譯器報告這些錯誤,爲src.get_char();

error: no method named get_char found for type () in the current scope

println!("{}", src.look);

attempted access of field look on type () , but no field with that name was found

我無法找出什麼我已經錯過了。

回答

7

Source::new沒有指定返回類型,因此返回()(空元組,也稱爲單位)。

因此,src的類型爲(),它沒有get_char方法,這是錯誤消息告訴你的。

所以,首先,我們設置一個合適的簽名newfn new() -> Source。現在,我們得到:

error: not all control paths return a value [E0269] 
    fn new() -> Source { 
     Source {look: '\0'}; 
    } 

這是因爲導致鏽病是一種表達式語言,幾乎一切都是表達式,除非分號是用來表達轉換成一個聲明。你可以寫new之一:

fn new() -> Source { 
    return Source { look: '\0' }; 
} 

或者:

fn new() -> Source { 
    Source { look: '\0' } // look Ma, no semi-colon! 
} 

魯斯特後者是更地道。

所以,讓我們做到這一點,現在我們得到:

error: cannot borrow immutable local variable `src` as mutable 
    src.get_char(); 
    ^~~ 

這是因爲src聲明不變(默認值),因爲它是可變的,你需要使用let mut src

現在一切正常!


最終代碼:

use std::io::Read; 

struct Source { 
    look: char 
} 

impl Source { 
    fn new() -> Source { 
     Source {look: '\0'} 
    } 

    fn get_char(&mut self) { 
     self.look = 'a'; 
    } 
} 

fn main() { 
    let mut src = Source::new(); 
    src.get_char(); 

    println!("{}", src.look); 
} 

注:有一個警告,因爲std::io::Read是未使用的,但我相信你打算使用它。

+0

..但我認爲鏽有_return類型推斷_因爲許多新的語言有。爲什麼它不能從我寫的行中推斷'new'的返回類型? – deepmax

+5

@deepmax:Rust在函數*中有類型推斷*,但要求函數簽名是明確的。但是,即使它確實如此,也會得出結論:由於分號,「new」應返回「()」。 Source {look:'\ 0'}'的類型是'Source',但Source {look:'\ 0'};'(帶分號)的類型是'()'。 –