Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a formatted String out of a literal in Rust?

I'm about to return a string depending the given argument.

fn hello_world(name:Option<String>) -> String {
    if Some(name) {
        return String::formatted("Hello, World {}", name);
    }
}

This is a not available associated function! - I wanted to make clear what I want to do. I browsed the doc already but couldn't find any string builder functions or something like that.

like image 579
xetra11 Avatar asked Jun 12 '16 18:06

xetra11


2 Answers

Use the format! macro:

fn hello_world(name: Option<&str>) -> String {
    match name {
        Some(n) => format!("Hello, World {n}"),
        None => format!("Who are you?"),
    }
}

In Rust, formatting strings uses the macro system because the format arguments are typechecked at compile time, which is implemented through a procedural macro.

There are other issues with your code:

  1. You don't specify what to do for a None - you can't just "fail" to return a value.
  2. The syntax for if is incorrect, you want if let to pattern match.
  3. Stylistically, you want to use implicit returns when it's at the end of the block.
  4. In many (but not all) cases, you want to accept a &str instead of a String.

See also:

  • Is there a way to pass named arguments to format macros without repeating the variable names?
like image 162
Shepmaster Avatar answered Oct 01 '22 12:10

Shepmaster


Since Rust 1.58 it's possible to use named parameters, too.

fn hello_world(name: Option<&str>) -> String {
    match name {
        Some(n) => format!("Hello, World {n}"),
        None => format!("Who are you?"),
    }
}
like image 29
Mr. R Avatar answered Oct 01 '22 14:10

Mr. R