I am trying to learn rust by building an app which models a graph of domain concepts. The "nodes" in the concept graph are references to other structs (stored in the same graph). The intent is to process/navigate through a network of references, and then publish results by looking inside the reference into the main concept objects.
I'm getting this cryptic error below. I can make it go away by pulling the declaration of the Container object into run, but I'd like to understand a bit deeper about what rust is complaining about, and what's the idiomatic way to create a concept graph that I am trying to build?
thanks!
#![allow(dead_code)]
#![allow(unused_variables)]
use std::collections::BTreeMap;
#[derive(Debug)]
pub struct Type1 {
id: u8,
name: String,
}
#[derive(Debug)]
pub struct Container<'a> {
t1coll: BTreeMap<u8, Type1>,
t1refcoll: BTreeMap<u8, &'a Type1>,
}
impl<'a> Container<'a> {
fn new() -> Self {
Container {
t1coll: BTreeMap::new(),
t1refcoll: BTreeMap::new(),
}
}
}
pub fn run(c: &mut Container) {
c.t1coll.insert(1, Type1{id: 3, name: "t11".to_string(),});
let rt1: &Type1;
match c.t1coll.get(&1) {
Some(t1) => rt1 = t1,
None => println!("Not found"),
}
c.t1refcoll.insert(1, rt1);
}
pub fn main() {
let mut cont = Container::new();
run(&mut cont);
println!("{:?}", cont);
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0623]: lifetime mismatch
--> src/main.rs:34:27
|
26 | pub fn run(c: &mut Container) {
| --------------
| |
| these two types are declared with different lifetimes...
...
34 | c.t1refcoll.insert(1, rt1);
| ^^^ ...but data from `c` flows into `c` here
error: aborting due to previous error
For more information about this error, try `rustc --explain E0623`.
error: could not compile `playground`.
To learn more, run the command again with --verbose.