Unit Type in Rust

Pascal Precht
InstructorPascal Precht

Share this video with your friends

Send Tweet
Published 3 years ago
Updated 2 years ago

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.

Instructor: [00:00] The unit type in Rust, also called the zero-tuple type, is a type that is useful when there's no meaningful value to carry but a type is still necessary. Everything in Rust has a type. Even this function sayHello(), which simply prints Hello, implicitly returns the unit type.

[00:19] We can run this function and see that as expected, it will say, "Hello." Once we change the return type of the function without updating the return type annotation, we'll see that there's going to be a compile error.

[00:34] Let's say we introduce a variable hello and store the string "Hello" in there. We then replace the "Hello" string here with a placeholder and pass the hello variable to println!. Last but not least, we'll return hello from this function.

[00:51] At this point, sayHello no longer returns the unit type, but a string slice reference. If we run the code now, Rust will complain that it expected a unit type as a return value, but it found a string slice reference. This, again, is because the function sayHello implicitly returns the unit type.

J. Matthew
J. Matthew
~ 3 years ago

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

Pascal Precht
Pascal Prechtinstructor
~ 3 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.