gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:23:35 28 4
gpt4 key购买 nike

关闭。这个问题是not reproducible or was caused by typos .它目前不接受答案。












想改善这个问题吗?更新问题,使其成为 on-topic对于堆栈溢出。

去年关闭。




Improve this question




我是 Rust 的新手。
我尝试创建一个 Point实现 Eq 的结构和 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 { }

每当我尝试编译程序时,我都会在这一行上收到一个错误: 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)

据我了解, ()就像 void类型,当你把它包裹起来时 Result像这样: Result<(), Error> ,你基本上期待 void键入但您也会发现错误。这样对吗?在这种情况下,为什么会出现编译错误?

最佳答案

您的分号 ;将该行变成 expression statement ,防止从函数返回结果。这在 Rust 编程语言 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 中时,我得到:
   |
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 来代替。)

关于rust - 预期枚举 `std::result::Result` ,找到 (),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60020738/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com