我很难理解如何插入数字并以正确的格式返回它。我开始使用返回String
的函数,但编译器需要&'static str
。我已经阅读了to_owned
,但它还没有点击我的脑袋。什么是"权利"做我尝试的方法?
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
这不是String to &'static str
的重复 - 我试图计算如何用字符串插入整数然后返回&static str
。