我想返回一个向量的元素:
struct EntryOne {
pub name: String,
pub value: Option<String>,
}
struct TestVec {}
impl TestVec {
pub fn new() -> TestVec {
TestVec {}
}
pub fn findAll(&self) -> Vec<EntryOne> {
let mut ret = Vec::new();
ret.push(EntryOne {
name: "foo".to_string(),
value: Some("FooVal".to_string()),
});
ret.push(EntryOne {
name: "foo2".to_string(),
value: Some("FooVal2".to_string()),
});
ret.push(EntryOne {
name: "foo3".to_string(),
value: None,
});
ret.push(EntryOne {
name: "foo4".to_string(),
value: Some("FooVal4".to_string()),
});
ret
}
pub fn findOne(&self) -> Option<EntryOne> {
let mut list = &self.findAll();
if list.len() …Run Code Online (Sandbox Code Playgroud) 我lazy_static用来留HashMap在记忆中.有两种方法,我添加和获取元素,但我有一些生命周期的问题.
这是我的代码:
#[macro_use]
extern crate lazy_static;
use std::sync::Mutex;
use std::collections::HashMap;
lazy_static! {
static ref HASHMAP: Mutex<HashMap<String, Foo>> = Mutex::new({
let mut m = HashMap::new();
m.insert("one".to_string(), Foo{param1:"foo1".to_string(), param2:"foo2".to_string()} );
m.insert("two".to_string(), Foo{param1:"bar1".to_string(), param2:"bar2".to_string()});
m
});
}
pub struct Foo{
param1: String,
param2: String,
}
pub fn ins_val(name: String, f: Foo){
HASHMAP.lock().unwrap().insert(name, f);
}
pub fn get_val(k: &str) -> Option<&Foo>{
HASHMAP.lock().unwrap().get(k)
}
Run Code Online (Sandbox Code Playgroud)
这是错误:
HASHMAP.lock().unwrap().get(k)
^^^^^^^^^^^^^^^^^^^^^^^
reference must be valid for the anonymous lifetime #1 defined on the block
Run Code Online (Sandbox Code Playgroud)