为什么Rust在main函数中没有返回值,以及无论如何如何返回值? [英] Why does Rust not have a return value in the main function, and how to return a value anyway?

查看:96
本文介绍了为什么Rust在main函数中没有返回值,以及无论如何如何返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Rust中,主要功能的定义如下:

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?

推荐答案

在出现错误的情况下,在这种情况下返回的错误代码为1.使用 File :: open("bar.txt").expect(找不到文件"); ,将返回错误值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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆