gpt4 book ai didi

syntax - 为什么宏调用后没有分号?

转载 作者:行者123 更新时间:2023-11-29 08:11:24 25 4
gpt4 key购买 nike

我正在学习我在 Rust 上找到的一些教程,我遇到了一些我的 Java/C/C++ 思维无法理解的东西:

impl fmt::Display for Matrix {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})\n({}, {})", self.0, self.1, self.2, self.3)
}
}

我不明白 write! 宏调用末尾缺少分号。如果我添加它,我会从编译器中得到一个错误。我猜测,如果分号不存在,那么 write!Result 将用作 fmt 的返回值,但任何人都可以提供一个更具体地解释为什么会这样,以及它是否总是适用?

最佳答案

write宏使用 write_fmt()方法来自 std::fmt::Write 或来自 std::io::Write ;都返回 Result<(), Error>并且您需要省略分号才能将其作为 fmt() 的输出.

来自 The Rust Book , 第一版:

Rust functions return exactly one value, and you declare the typeafter an ‘arrow’, which is a dash (-) followed by a greater-than sign(>). The last line of a function determines what it returns. You’llnote the lack of a semicolon here. If we added it in we wouldget an error.

This reveals two interesting things about Rust: it is anexpression-based language, and semicolons are different fromsemicolons in other ‘curly brace and semicolon’-based languages.

关于syntax - 为什么宏调用后没有分号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46969733/

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