Rust 中单元类型的目的是什么? [英] What is the purpose of the unit type in Rust?

查看:34
本文介绍了Rust 中单元类型的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rust 有 unit 类型(),一种具有单个零大小值的类型.此单元类型的值也使用 () 指定.

Rust has the unit type, (), a type with a single zero-size value. The value of this unit type is also specified using ().

单位类型及其值的用途是什么?它是一种避免像其他语言一样使用 null(或 nil)的机制吗?

What is the purpose of the unit type and its value? Is it a mechanism to avoid using null (or nil) like other languages have?

推荐答案

()() 类型的值,其目的是无用.

() is a value of the type () and its purpose is to be useless.

Rust 中的一切都是一个表达式,返回无"的表达式实际上返回 ().如果您有一个没有返回类型的函数,但无论如何返回 () 以外的内容,编译器将给出错误.例如

Everything in Rust is an expression, and expressions that return "nothing" actually return (). The compiler will give an error if you have a function without a return type but return something other than () anyway. For example

fn f() {
    1i32 // error: mismatched types: expected `()` but found `int`
}

() 也有实际用途.有时我们不关心泛型类型,而 () 使这一点变得明确.

There are practical uses for () too. Sometimes we don't care about a generic type, and () makes this explicit.

例如,Result<(), String> 可以用作函数的返回类型,该函数要么成功完成要么由于各种原因失败.

For example, a Result<(), String> can be used as return type for a function that either completes successfully or fails for a variety of reasons.

这篇关于Rust 中单元类型的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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