expected enum `std::result::Result`, found () [closed]

只谈情不闲聊 提交于 2020-12-08 06:56:09

问题


I'm new to Rust.
I try to create a Point struct that implements Eq and Debug, so I did this:

use std::fmt;

pub struct Point {
    x: f32,
    y: f32,
}

impl Point {
    pub fn new(x: f32, y: f32) -> Point {
        Point{
            x: x,
            y: y,
        }
    }
}

impl fmt::Debug for Point {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "({}, {})", self.x, self.y);
    }
}

impl PartialEq for Point {
    fn eq(&self, other: &Self) -> bool {
        return self.x == other.x && self.y == other.y;
    }
}

impl Eq for Point { }

Whenever I try to compile the program, I get an error on this line: fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {, saying:

mismatched types

expected enum `std::result::Result`, found ()

note: expected type `std::result::Result<(), std::fmt::Error>`
         found type `()`rustc(E0308)

From what I understand, () is like the void type, and when you wrap it around Result like this: Result<(), Error>, you basically expect the void type but you also catch errors. Is it right? In that case, why do I get a compilation error?


回答1:


Your semicolon ; turns that line into an expression statement, preventing the Result from being returned from the function. This is covered in The Rust Programming Language here:

Expressions do not include ending semicolons. If you add a semicolon to the end of an expression, you turn it into a statement, which will then not return a value.

When I copy your code into https://play.rust-lang.org, I get:

   |
18 |     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
   |        ---                                       ^^^^^^^^^^^ expected enum `std::result::Result`, found `()`
   |        |
   |        implicitly returns `()` as its body has no tail or `return` expression
19 |         write!(f, "({}, {})", self.x, self.y);
   |                                              - help: consider removing this semicolon
   |
   = note:   expected enum `std::result::Result<(), std::fmt::Error>`
           found unit type `()`

If you remove the semicolon, it works. (You could also have chosen to add an explicit return instead.)



来源:https://stackoverflow.com/questions/60020738/expected-enum-stdresultresult-found

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!