Search code examples
rusttype-conversionrust-rustlings

Rustlig if2 trying to convert 1 to "1" inside the function foo_if_fizz


I'm new to rust and I'm looking for a way to convert 1 to "1" at compile time;

pub fn foo_if_fizz(fizzish: &str) -> &str {
    if fizzish == "fizz" {
        "foo"
    } else {
        &(1.to_string()). <-- returns a reference to data owned by the current function
    }
}

this error is completely logical, I'm aware of it. But how can we manage to do (Even if it requires the use of unsafe)?

I have an idea but I don't know if it is feasible. I could allocate some memory space at compile time, like for example "0" which is an i32. Then inside the function, I could get the address then access the memory directly and change the value inside.

The questing is what is the best way


Solution

  • I would assume you are looking for this one:

    extern crate lazy_static;   
    use lazy_static::lazy_static;
    
    pub fn foo_if_fizz(fizzish: &str) -> &str {
        if fizzish == "fizz" {
            "foo"
        } else {
            lazy_static! {
                static ref ONE: String = 1.to_string();
            }
            &ONE
        }
    }
    

    Nevertheless, the only correct answer to the question at hand is Friedman's "1"!