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?