预期枚举`std::result::Result`,找到()

are*_*ler 12 rust

我是 Rust 的新手。
我尝试创建一个Point实现Eqand的结构Debug,所以我这样做了:

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 { }
Run Code Online (Sandbox Code Playgroud)

每当我尝试编译程序时,我都会在这一行上收到一个错误:fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {,说:

mismatched types

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

note: expected type `std::result::Result<(), std::fmt::Error>`
         found type `()`rustc(E0308)
Run Code Online (Sandbox Code Playgroud)

据我所知,()就像void类型一样,当你Result像这样包装它时:Result<(), Error>,你基本上期望void类型,但你也会捕获错误。这样对吗?在这种情况下,为什么会出现编译错误?

jtb*_*des 18

您的分号;将该行转换为表达式语句,从而防止从函数返回结果。这是覆盖在锈病编程语言在这里

表达式不包括结束分号。如果在表达式的末尾添加分号,则将其转换为语句,然后该语句不会返回值。

当我将您的代码复制到https://play.rust-lang.org 时,我得到:

   |
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 `()`

Run Code Online (Sandbox Code Playgroud)

如果删除分号,它会起作用。(您也可以选择添加显式return。)