I'm stumped on how to interpolate a number and return it in the correct format. I started with the function returning String
but then the compiler wanted &'static str
. I've read about to_owned
but it's not clicking in my head yet. What is the "right" way to do what I'm attempting?
fn ordinal_name(num: i32) -> &'static str {
if num == 1 {
"1st"
} else if num == 2 {
"2nd"
} else if num == 3 {
"3rd"
} else {
format!("{}th", num)
}
}
fn main() {
println!("{}", ordinal_name(5));
}
error[E0308]: mismatched types
--> src/main.rs:9:9
|
1 | fn ordinal_name(num: i32) -> &'static str {
| ------------ expected `&'static str` because of return type
...
9 | format!("{}th", num)
| ^^^^^^^^^^^^^^^^^^^^ expected reference, found struct `std::string::String`
|
= note: expected type `&'static str`
found type `std::string::String`
= note: this error originates in a macro outside of the current crate
This is not a duplicate of String to &'static str
- I'm trying to figure how to interpolate an integer with a string and then return a &static str
.