1. 7
    Unit Type in Rust
    1m 12s

Unit Type in Rust

InstructorPascal Precht

Share this video with your friends

Send Tweet

Everything in Rust has a type. Even functions that don't seem to return anything. In such and similar cases, we're dealing with a Unit Type. Learn about it in this lesson.

J. Matthew
~ 4 years ago

This is the same as void in other languages? Interesting that it uses the tuple syntax.

Pascal Prechtinstructor
~ 4 years ago

Yes, I'd say it is comparable to void in other languages. The main difference being however that () is also a value (of type ()), while void has no value.

This StackOverflow answer explains it nicely:

If you're coming from a C-like language (C, C++, Java, etc.), you can think of unit as being like void. It is the type you return when you don't want to return anything. Type theorists will point out that unit is not like void, because unit has exactly 1 value whereas void has 0 values. In practice, the amount of information you can store in both types is the same (0 bits), although languages that use unit tend to be nicer to work with because you can treat it as you would any other value. You can store it in a variable, struct, collection, or anywhere else you could store a value. You can pass as an argument or return it as a result. You can create a reference to it. Etc.