预期枚举`std::result::Result`,找到() [英] expected enum `std::result::Result`, found ()
问题描述
我是 Rust 的新手.
我尝试创建一个实现 Eq
和 Debug
的 Point
结构,所以我这样做了:
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 { }
每当我尝试编译程序时,我都会在这一行收到错误:fn fmt(&self, f: &mut fmt::Formatter<'_>) ->fmt::Result {
,说:
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)
据我所知,()
就像 void
类型,当你把它包裹在 Result
周围时,像这样:Result<(), Error>
,您基本上期望 void
类型,但您也会捕获错误.这样对吗?在这种情况下,为什么会出现编译错误?
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?
推荐答案
你的分号 ;
将该行变成 表达式语句,防止从函数返回结果.这在 Rust 编程语言 这里:
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.
当我将您的代码复制到 https://play.rust-lang.org 时,我得到:
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 `()`
如果你去掉分号,它就起作用了.(您也可以选择添加显式return
.)
If you remove the semicolon, it works. (You could also have chosen to add an explicit return
instead.)
这篇关于预期枚举`std::result::Result`,找到()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!