问题
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