Start learning free

LESSON 46 OF 293 · FUNCTIONS I

Returning a String in Rust: println! vs format!

Practice Read the full explanation

We've written a program and expected it to print Hey, Andy but when we run it we get some errors.

Fix our code so that it works and prints what we want.

STEP 1 OF 1
    Ctrl + Enter to check

    RUST · FUNCTIONS I

    Buggy Code Print Instead Of Return in Rust, explained

    Problem overview

    The program has two functions. get_greeting is meant to build the greeting for a name and hand it back as a String. main_function calls it with "Andy".to_string(), stores the result in greeting and prints it. The output should be Hey, Andy, printed once.

    The starter code does not compile. The compiler reports mismatched types: it expected a String and found ().

    What the compiler is telling you

    The signature fn get_greeting(name: String) -> String is a promise: whatever happens inside, the function ends with a String. The body of the starter code is a single line:

    println!("Hey, {}", name);
    

    println! writes text to the screen and gives nothing back. The value of the call is (), the unit type, which means "no value". The line ends with a semicolon, so the body has no final expression and no return. A function like that evaluates to (), and () is not a String. The error reads:

    error[E0308]: mismatched types
      expected `String`, found `()`
      implicitly returns `()` as its body has no tail or `return` expression

    The wording is worth remembering. "Implicitly returns ()" is how Rust describes a function whose body never produces the promised value.

    Printing and returning are different jobs

    Two actions are easy to confuse:

    • Printing shows text to whoever runs the program. The program itself can't use that text afterwards.
    • Returning hands a value to the code that called the function. That code can store it, compare it, pass it on or print it.

    Here the caller already does the printing: main_function has a println!("{}", greeting) of its own. So get_greeting only needs to build the text and give it back. If it printed the greeting as well, the text would appear twice, and the function still would not have a String to return.

    The tool for the job: format!

    The macro format! takes the same format string and arguments as println!, but instead of printing it returns the finished text as a new String. That is exactly the value the function has to produce.

    let s: String = format!("{}-{}", 1, 2);
    println!("{}", s); // prints: 1-2
    

    Step by step

    1. Leave main_function alone. It already calls get_greeting, keeps the result and prints it.
    2. In get_greeting, replace println! with format!, keeping the same format string "Hey, {}" and the argument name.
    3. Return the result. The reference solution writes return in front and ends the line with a semicolon.

    The solution in Rust

    fn get_greeting(name: String) -> String {
        return format!("Hey, {}", name);
    }
    
    fn main_function() {
        let greeting = get_greeting("Andy".to_string());
        println!("{}", greeting);
    }
    

    With name equal to "Andy", format! builds the String Hey, Andy, return sends it to main_function, and the only println! in the program prints it once.

    Rust details that matter here

    return is optional at the end of a function

    In Rust, a function's last expression is its return value when it has no trailing semicolon. This version is equivalent to the reference solution and is the more common style:

    fn get_greeting(name: String) -> String {
        format!("Hey, {}", name)
    }
    

    The semicolon is the whole difference. format!("Hey, {}", name); with a semicolon throws the value away and brings back the same () error. The keyword return is needed for early exits from the middle of a function.

    Why name is a String

    The function takes name: String, an owned string, which is why the caller writes "Andy".to_string(): a string literal has type &str, and to_string() turns it into an owned String. Passing the literal directly would be a type mismatch.

    Common mistakes

    • Keeping println! and adding a return. Printing inside the function as well as in the caller shows the greeting twice.
    • Changing the return type to nothing. Removing -> String while keeping the caller as it is makes greeting in main_function a (), which can't be printed with {}.
    • Forgetting that a trailing semicolon discards the value.

    Key takeaways

    • println! prints and evaluates to (); format! builds and returns a String.
    • A function with a -> String signature must end with a String, through return or a final expression without a semicolon.
    • Let the function return the value and let the caller decide whether to print it.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free