1

This is a total Rust newbie question here, so I'd greatly appreciate anyone being patient enough to explain this to me. I've got the following code:

fn main() {
    let api_key = match read_api_key(Path::new("../stockfighter-api.key")) {
        Ok(key) => key,
        Err(_) => panic!("Unable to read key!"),
    };
    println!("API Key: {}", api_key);
}

fn read_api_key(path: &Path) -> Result<String, io::Error> {
    let mut f = File::open(path)?;
    let mut buffer = String::new();
    f.read_to_string(&mut buffer)?;

    Ok(buffer.trim().to_string())
}

But the final call to .to_string() in my function there seems superfluous to me: why allocate a second String in that function, when there's already one there that I just need part of? However, if I try to rewrite the function like so:

fn read_api_key(path: &Path) -> Result<&str, io::Error> {
    let mut f = File::open(path)?;
    let mut buffer = String::new();
    f.read_to_string(&mut buffer)?;

    Ok(buffer.trim())
}

I end up with the following error:

src/main.rs:31:8: 31:14 error: `buffer` does not live long enough
src/main.rs:31     Ok(buffer.trim())
                      ^~~~~~

And the error makes sense to me, but I don't know how to avoid the second String allocation any other way...

Can anyone walk me through what I'm missing or misunderstanding here?

Kornel
  • 97,764
  • 37
  • 219
  • 309
Karl M. Davis
  • 606
  • 1
  • 7
  • 22
  • 2
    @Shepmaster re-reading the question, I think it's more related to stackoverflow.com/questions/31276059 instead. AFAICT the crux of the issue is that Karl wants to trim the string in-place, but the .trim() method returns a slice. – Lambda Fairy Aug 24 '16 at 09:54
  • @LambdaFairy although `trim` removes from the left and the right, and most of those answers only allow for trimming from the right. – Shepmaster Aug 24 '16 at 13:47
  • @LambdaFairy: Yeah, I don't have the code in question in front of me right now, but the question and answer you referenced there do seem more correct. Thanks! – Karl M. Davis Aug 24 '16 at 19:43

0 Answers0