Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot return value owned by a function

I’m confused with something that should be very simple. I have a function that takes user input, splits it into vector by spaces and return ssaid vector:

fn get_rotors() -> Vec<&'static str> {
    let mut foo: String = String::new();   # compiler says "foo" is borrowed from here
    println!("Enter a set of 3 Roman numerals separated by spaces.
            \nFor example: I IV VI");
    let mut ids_input: String = String::new();
    match stdin().read_line(&mut ids_input) {
        Ok(n) => foo = n.to_string().clone(),
        Err(_Error) => foo = "".to_string(),
    };
    let rotor_vec: Vec<_> = foo.split(" ").collect();
    return rotor_vec
}

In this version I get a compiler error that I can’t return a value owned by the function.

I thought that maybe I should try and dereference it:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

--snip--
    return *rotor_vec

But here I get: expected struct Vec<&'static str> found slice [&str].

Ok, says I, I’ll try explicitly converting it to vector when returning:

--snip--
return *rotor_vec.to_vec()

Same result.

I tried using clone(), which also didn’t work, so I can’t seem to return value from function and I have no idea why it is so.

>Solution :

Your function claims to return a vector of string slices that live forever (&'static str). But you actually return a vector of string slices that point into the local foo variable, which goes out of scope as the function leaves, so those slices would dangle.

What you really want is to return a Vec<String>. Which means that after the split, you need to turn each slice into an owned string with to_owned.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading