What is the purpose of the unit type in Rust?

后端 未结 2 2140
梦谈多话
梦谈多话 2020-12-09 14:42

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

What is

2条回答
  •  抹茶落季
    2020-12-09 15:13

    () 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.

提交回复
热议问题