为什么 Rust 在 main 函数中没有返回值,以及如何返回值? [英] Why does Rust not have a return value in the main function, and how to return a value anyway?
问题描述
在 Rust 中,main 函数是这样定义的:
In Rust the main function is defined like this:
fn main() {
}
虽然这个函数不允许返回值.为什么一种语言不允许返回值,有没有办法返回一些东西?我能否安全地使用 C exit(int)
函数,或者这会导致泄漏等等?
This function does not allow for a return value though. Why would a language not allow for a return value and is there a way to return something anyway? Would I be able to safely use the C exit(int)
function, or will this cause leaks and whatnot?
推荐答案
截至 Rust 1.26,main
可以返回一个Result
:
As of Rust 1.26, main
can return a Result
:
use std::fs::File;
fn main() -> Result<(), std::io::Error> {
let f = File::open("bar.txt")?;
Ok(())
}
在这种情况下返回的错误代码是1,以防出错.使用 File::open("bar.txt").expect("file not found");
会返回错误值 101(至少在我的机器上).
The returned error code in this case is 1 in case of an error. With File::open("bar.txt").expect("file not found");
instead, an error value of 101 is returned (at least on my machine).
此外,如果您想返回更一般的错误,请使用:
Also, if you want to return a more generic error, use:
use std::error::Error;
...
fn main() -> Result<(), Box<dyn Error>> {
...
}
这篇关于为什么 Rust 在 main 函数中没有返回值,以及如何返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!