Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the unit type in Rust?

Tags:

rust

unit-type

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 the purpose of the unit type and its value? Is it a mechanism to avoid using null (or nil) like other languages have?

like image 562
Will Avatar asked Jul 19 '14 16:07

Will


People also ask

What is meant by unit type?

In the area of mathematical logic and computer science known as type theory, a unit type is a type that allows only one value (and thus can hold no information). The carrier (underlying set) associated with a unit type can be any singleton set.

How do I return in Rust?

The return keyword can be used to return a value inside a function's body. When this keyword isn't used, the last expression is implicitly considered to be the return value. If a function returns a value, its return type is specified in the signature using -> after the parentheses () .


1 Answers

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

like image 181
A.B. Avatar answered Oct 13 '22 18:10

A.B.