4

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
user1491929
  • 654
  • 8
  • 16
  • I think this really needs a reference to [`Cow`](https://doc.rust-lang.org/std/borrow/enum.Cow.html), the linked duplicate is not good enough. – Stefan Feb 10 '18 at 12:59
  • https://stackoverflow.com/questions/36706429/return-either-a-borrowed-or-owned-type-in-rust/36707468#36707468 is a start – Stefan Feb 10 '18 at 13:00
  • [Example in playground](https://play.rust-lang.org/?gist=cae31659a0caa396c2702039b5e16964&version=stable) – Stefan Feb 10 '18 at 13:01
  • *I'm trying to figure how to interpolate an integer with a string and then return a `&static str`* => "I'm trying to figure how to [create a `String`] and then return a `&static str`". This is indeed a duplicate; the path you take to create the `String` doesn't matter. `format!` creates a `String`. – Shepmaster Feb 10 '18 at 15:10
  • As an aside, your function will not produce the correct output for numbers like `23`. – Shepmaster Feb 10 '18 at 15:18
  • @Shepmaster, you're right. Luckily this only needs to go to 12 ;) – user1491929 Feb 14 '18 at 01:34

0 Answers0