String argument in Rust

Dec 02, 2024

You want to pass a string literal like "This is an error message". In this case, we should define a function with a string slice &str as an argument instead of String argument.

fn my_print(text: &str) {
    ...
}

my_print("This is an error message");

To pass a String to it, you can pass a reference.

let err_msg = format!("Error number {}", 5);  // err_msg is a String.
my_print(&err_msg);