【发布时间】:2016-03-08 17:03:37
【问题描述】:
是否可以从集合中获取一个值并对其应用只接受self 而不是&self 的方法?
最小的工作示例
我想写的是类似于:
use std::collections::HashMap;
fn get<B>(key: i32, h: HashMap<i32, Vec<(i32, B)>>) -> i32 where B: Into<i32> {
let v: &Vec<(i32, B)> = h.get(&key).unwrap();
let val: &B = v.first().unwrap().1;
// Do something to be able to call into
// I only need the value as read-only
// Does B have to implement the Clone trait?
return val.into();
}
我曾尝试在编译器错误后到处运球mut试图安抚编译器错误,但这确实是愚蠢的差事。
use std::collections::HashMap;
fn get<B>(key: i32, mut h: HashMap<i32, Vec<(i32, B)>>) -> i32 where B: Into<i32> {
let mut v: &Vec<(i32, B)> = h.get_mut(&key).unwrap();
let ref mut val: B = v.first_mut().unwrap().1;
return (*val).into();
}
这种事情是可能的还是B 必须实现Clone 特征?
我也试过了:
- 不安全
- 原始指针
我没试过:
Box- 我没有遇到的其他 Rust 结构, 我提到这一点是为了明确声明我没有 省略了我知道的任何方法。
【问题讨论】:
标签: rust readonly move-semantics traits