小编div*_*ero的帖子

实现Index trait时无约束的生命周期错误

我有一个拥有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)

rust

6
推荐指数
1
解决办法
892
查看次数

在Scala中创建新对象后的代码块

我有一个构造函数定义为

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无济于事。

constructor scala

3
推荐指数
1
解决办法
371
查看次数

将数据写入 go lang 通道的成本?

我有一个list( containers/list) 包含一个[]string. 我经常通过频道发送这个。我试图了解这种通信的成本有多高。一般情况是在发送时将正在发送的数据的浅拷贝复制到缓冲区,然后在接收时在另一侧重新复制吗?那么发送和接收并不比浅拷贝更昂贵?一般有一些问题吗?

go channels

3
推荐指数
1
解决办法
593
查看次数

Deref与泛型的强制

我正在尝试编写一个参数化函数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)

generics dereference rust

3
推荐指数
1
解决办法
182
查看次数

标签 统计

rust ×2

channels ×1

constructor ×1

dereference ×1

generics ×1

go ×1

scala ×1