Unit Type in Rust

Pascal Precht
InstructorPascal Precht
Share this video with your friends

Social Share Links

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.

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.