Why calling macro(println!) returns no value?

I am reading function part of The Rust Programming Language.
Calling function is an expression and calling macro is an expression.
So I want to know what value is returned for calling macro.
Here is the code:

  fn main() {
      let x = println!("Hello, world!");
      println!("The value is {}", x);

Using Cargo run, doesn’t work.
Error message

error[E0277]: `()` doesn't implement `std::fmt::Display`
 --> src/main.rs:3:33
3 |     println!("The value is {}", x);
  |                                 ^ `()` cannot be formatted with the default formatter
  = help: the trait `std::fmt::Display` is not implemented for `()`
  = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
  = note: required by `std::fmt::Display::fmt`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0277`.

By my current level, I don’t understand the error message.

Why calling macro(println!) returns no value?

Because there is no value to be returned. To be strict - it returns value of type “unit” (()) with its only valid value (()). This type cannot be printed using {} format, but can be with {:?}. To make this work you may do something like:

fn main() {
    let x = println!("Hello, world!");
    println!("The value is {:?}", x);
1 Like

Thanks. I hope the more I continue to read, the more I will be able to understand what is type “unit” (())

What would you expect it to return is the other question?

1 Like

Unit type is the type what void functions return. Python calls it None, and kotlin calls it Nothing. I personally prefer the name Nothing as it’s just nothing, contains nothing and nothing useful at all, but still is a thing so we can call its name, nothing.

No, Kotlin’s “no return value” type is Unit, not Nothing.

Rust (), Kotlin Unit, Java Void are the “singleton” type where there is exactly one valid value ((), Unit.VALUE, null).†

Rust !, Kotlin Nothing are the “uninhabited” type, where there is no possible value of that type.

† Java is special: Void has no inhabitants, but as all variables are nullable, null is a valid value for a place typed at Void. To add to the confusion, returning void is distinct from returning Void, as void actually means that the function doesn’t return anything at the JVM Bytecode level, and you can’t assign it to a variable at the language level, whereas Void is a class with no inhabitants such that a place typed at Void can only be null.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.