I am attempting, completely unsuccessfully, to use Rust to write a verifier for a database that's part of a personal financial management system I've written. I've run into a lifetime puzzle. Here's a very cut-down version of my code that exhibits the issue:
1 extern crate rusqlite;
2
3 use std::env;
4 use rusqlite::Connection;
5 use rusqlite::Statement;
6
7 // Types
8 struct Globals<'a> {
9 new_guid: &'a mut Statement<'a>,
10 }
11
12 fn main() {
13 const DB_FILE_INDEX: usize = 1;
14
15 // Open the database
16 let db = Connection::open(env::args().nth(DB_FILE_INDEX).unwrap()).unwrap();
17
18 // Prepare queries we will need later
19 let mut new_guid_stmt = db.prepare("select lower(hex(randomblob(16)))").unwrap();
20
21 let mut globals = Globals {
22 new_guid: &mut new_guid_stmt,
23 };
24 }
The compiler (1.12.0) says:
error: new_guid_stmt
does not live long enough
--> main.rs:22:24
|
22 | new_guid: &mut new_guid_stmt,
| ^^^^^^^^^^^^^
|
note: reference must be valid for the block suffix following statement 1 at 16:80...
--> main.rs:16:81
|
16 | let db = Connection::open(env::args().nth(DB_FILE_INDEX).unwrap()).unwrap();
| ^
note: ...but borrowed value is only valid for the block suffix following statement 2 at 19:85
--> main.rs:19:86
|
19 | let mut new_guid_stmt = db.prepare("select lower(hex(randomblob(16)))").unwrap();
| ^
error: aborting due to previous error
The block suffix following lines 16 and 19 are the same! Can someone please explain what this thing is complaining about?
A general observation: it has been apparent for a very long time that the explanations of lifetime provided by the Rust Book and other sources are simply not adequate. They explain the syntax of how to annotate code with explicit lifetimes, but they do not explain the semantics; what the annotations mean is just not explained. A little searching of this forum and some googling reveals how much confusion has existed and continues to exist about this topic and for how long. I don't understand why the documentation problem hasn't been fixed after all this time that people have been clearly baffled by this. Perhaps the underlying subject itself is so arcane that it's extremely difficult to explain?
I hope someone can provide a satisfactory explanation for the issue I've run into above. Unless and until that happens, I have to put the use of Rust on my project on hold.