我有一个拥有a的结构HashMap<String, String>,
struct Test {
data: HashMap<String, String>,
}
Run Code Online (Sandbox Code Playgroud)
我试图实现Index这种类型的特征来映射到Indexhashmap 的实现(涉及其他逻辑,所以我不能公开hashmap).
如果我只是获取对hashmap中的值的引用,这是有效的:
impl<'b> Index<&'b str> for Test {
type Output = String;
fn index(&self, k: &'b str) -> &String {
self.data.get(k).unwrap()
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我想&Option<&String>摆脱它,就像data.get().所以我尝试了这个:
impl<'b, 'a> Index<&'b str> for Test {
type Output = Option<&'a String>;
fn index(&'a self, k: &'b str) -> &Option<&'a String> {
&self.data.get(k)
}
}
Run Code Online (Sandbox Code Playgroud)
这导致:
error[E0207]: the lifetime parameter `'a` is not constrained by the …Run Code Online (Sandbox Code Playgroud) 我有一个构造函数定义为
class Test{ var i = 0; println("constructor"); }
Run Code Online (Sandbox Code Playgroud)
我称之为
val t = new Test { println("codeblock"); i = 7; }
Run Code Online (Sandbox Code Playgroud)
结果是:
constructor
codeblock
defined class Test
t: Test = $anon$1@4a7b4f79
res3: Int = 7
Run Code Online (Sandbox Code Playgroud)
因此,我看到与new在同一行上的代码块被执行,就好像它是构造函数的一部分一样。我对此并不熟悉。
有人可以澄清这种行为和/或指向参考来解释此处的语义吗?我不确定如何使用Google进行搜索-寻找code block on same line as constructor call scala无济于事。
我有一个list( containers/list) 包含一个[]string. 我经常通过频道发送这个。我试图了解这种通信的成本有多高。一般情况是在发送时将正在发送的数据的浅拷贝复制到缓冲区,然后在接收时在另一侧重新复制吗?那么发送和接收并不比浅拷贝更昂贵?一般有一些问题吗?
我正在尝试编写一个参数化函数if_found_update,如果它存在,则更新散列中的值:
use std::collections::HashMap;
fn if_found_update<K, V>(data: &mut HashMap<K, V>, k: &K, v: &V, f: &Fn(&V, &V) -> V) -> bool
where K: std::cmp::Eq,
K: std::hash::Hash
{
if let Some(e) = data.get_mut(k) {
*e = f(e, v);
return true;
}
false
}
fn main() {
let mut h: HashMap<String, i64> = HashMap::new();
h.insert("A".to_string(), 0);
let one = 1 as i64;
fn update(e1: &i64, e2: &i64) -> i64 {
e1 + e2
};
let k: &str = &"A".to_string();
println!("{}",
if_found_update(&mut …Run Code Online (Sandbox Code Playgroud)