Rust之unit类型()

unit类型(unit type), 即 ()

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

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.

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.

unit type是一个类型,有且仅有一个值:(),即单位类型()既是一个类型,同时又是该类型的值。

单元类型()类似c/c++/java语言中的void。当一个函数并不需要返回值的时候,c/c++/java中函数返回void,rust则返回()。但语法层面上,void仅仅只是一个类型,该类型没有任何值;而单元类型()既是一个类型,同时又是该类型的值。

Rust标准库中使用单元类型()的一个例子是HashSet。一个HashSet只不过是HashMap的一个非常简单地包裹,写作:HashMap<T, ()>。HashMap的第二个泛型类型参数即用了单元类型()

可以用Result<(), MyErrorType>代替Option,某些开发者认为Result<(), MyErrorType>语义上能更简明地表示一个“结果”。

参考:
What is the purpose of the unit type in Rust?
Rust语言中的单位类型unit type是什么

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值