Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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?

like image 544
areller Avatar asked Feb 01 '20 20:02

areller


People also ask

What is enum result in rust?

Enum std::result::Result1.0. #[must_use] pub enum Result<T, E> { Ok(T), Err(E), } Result is a type that represents either success ( Ok ) or failure ( Err ). See the std::result module documentation for details.

What does OK () do in Rust?

It is an enum with the variants, Ok(T) , representing success and containing a value, and Err(E) , representing error and containing an error value. Functions return Result whenever errors are expected and recoverable.


1 Answers

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.)

like image 158
jtbandes Avatar answered Oct 12 '22 13:10

jtbandes