I have a section of code where the compiler gives errors :- tex has gone out of scope..... it is in the same section of code. Now I rearrange the code slightly and the problem goes away. As shown below.....
impl Handler for Server {
fn on_message(&mut self, msg: Message) -> Result<()> {
let mut methods: HashMap< String, fn(_,_) -> _> = HashMap::new();
methods.insert( "extcall".to_string(), extcall );
methods.insert( "add".to_string(), add );
println!("Got message: {:?}", msg);
let tex = msg.into_text().unwrap();
println!("Into text: {:?}", tex);
let v: Vec<&str> = tex.split_whitespace().collect();
println!("Words: {:?}, Length: {}", v, v.len());
let key = &v[0];
println!("Key: {:?}", key);
let result = methods[&key.to_string()] (&v[1], &v[2]);
self.out.send(result)
}
This one compiles ok!!
impl Handler for Server {
fn on_message(&mut self, msg: Message) -> Result<()> {
println!("Got message: {:?}", msg);
let tex = msg.into_text().unwrap();
println!("Into text: {:?}", tex);
let v: Vec<&str> = tex.split_whitespace().collect();
println!("Words: {:?}, Length: {}", v, v.len());
let key = &v[0];
println!("Key: {:?}", key);
let mut methods: HashMap< String, fn(_,_) -> _> = HashMap::new();
methods.insert( "extcall".to_string(), extcall );
methods.insert( "add".to_string(), add );
let result = methods[&key.to_string()] (&v[1], &v[2]);
self.out.send(result)
}
Can anyone explain the logic of this?
Message follows:-
cargo build (in directory: /home/rich/rust/ws_server/src)
Compiling ws_server v0.1.0 (file:///home/rich/rust/ws_server)
error[E0597]: `tex` does not live long enough
--> src/main.rs:32:28
|
32 | let v: Vec<&str> = tex.split_whitespace().collect();
| ^^^ borrowed value does not live long enough
...
42 | }
| - `tex` dropped here while still borrowed
|
= note: values in a scope are dropped in the opposite order they are created
p.s. Some of that code will be replaced, with json or messagepack ...