2016-06-17 72 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'};'(带分号)的类型是'()'。 –

相关问题