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

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

问题描述

Rust具有单位类型(),该类型具有单个零大小值.也可以使用()指定此单位类型的值.

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中的所有内容都是一个表达式,返回"nothing"的表达式实际上返回().如果您的函数没有返回类型,但无论如何都返回()以外的内容,则编译器将给出错误消息.例如

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天全站免登陆