This works:
fn user_add<'x>(data: &'x Input, db: &'x mut Database<'x>) -> HandlerOutput {
//let input: UserAddIn = json::decode(&data.post).unwrap();
//let username = input.username.as_bytes();
//let password = input.password.as_bytes();
db.put(b"Hi", b"hello");
//db.delete(username);
Ok("Hi".to_string())
}
This does not work:
fn user_add<'x>(data: &'x Input, db: &'x mut Database<'x>) -> HandlerOutput {
//let input: UserAddIn = json::decode(&data.post).unwrap();
//let username = input.username.as_bytes();
//let password = input.password.as_bytes();
let my_str = "hi".to_string();
let username = my_str.as_bytes();
db.put(username, b"hello");
//db.delete(username);
Ok("Hi".to_string())
}
Compiler output:
src/handlers.rs:85:17: 85:23 error: `my_str` does not live long enough
src/handlers.rs:85 let username = my_str.as_bytes();
^~~~~~
src/handlers.rs:80:77: 89:2 note: reference must be valid for the lifetime 'x as defined on the block at 80:76...
src/handlers.rs:80 fn user_add<'x>(data: &'x Input, db: &'x mut Database<'x>) -> HandlerOutput {
src/handlers.rs:81 //let input: UserAddIn = json::decode(&data.post).unwrap();
src/handlers.rs:82 //let username = input.username.as_bytes();
src/handlers.rs:83 //let password = input.password.as_bytes();
src/handlers.rs:84 let my_str = "hi".to_string();
src/handlers.rs:85 let username = my_str.as_bytes();
...
src/handlers.rs:84:32: 89:2 note: ...but borrowed value is only valid for the block suffix following statement 0 at 84:31
src/handlers.rs:84 let my_str = "hi".to_string();
src/handlers.rs:85 let username = my_str.as_bytes();
src/handlers.rs:86 db.put(username, b"hello");
src/handlers.rs:87 //db.delete(username);
src/handlers.rs:88 Ok("Hi".to_string())
src/handlers.rs:89 }
I've seen several questions about lifetime in Rust and I think the book is not that clear about it. I still use lifetimes as trial and error. This specific case has confused me because I've made several attempts fighting against the compiler and this is just the last error I got. If you have some Rust skills please consider editing the part about lifetimes in the book.