相关疑难解决方法(0)

为什么我不能在同一个结构中存储值和对该值的引用?

我有一个值,我想在我自己的类型中存储该值以及对该值内部内容的引用:

struct Thing {
    count: u32,
}

struct Combined<'a>(Thing, &'a u32);

fn make_combined<'a>() -> Combined<'a> {
    let thing = Thing { count: 42 };

    Combined(thing, &thing.count)
}
Run Code Online (Sandbox Code Playgroud)

有时候,我有一个值,我想在同一个结构中存储该值和对该值的引用:

struct Combined<'a>(Thing, &'a Thing);

fn make_combined<'a>() -> Combined<'a> {
    let thing = Thing::new();

    Combined(thing, &thing)
}
Run Code Online (Sandbox Code Playgroud)

有时,我甚至没有参考该值,我得到同样的错误:

struct Combined<'a>(Parent, Child<'a>);

fn make_combined<'a>() -> Combined<'a> {
    let parent = Parent::new();
    let child = parent.child();

    Combined(parent, child)
}
Run Code Online (Sandbox Code Playgroud)

在每种情况下,我都会收到一个错误,即其中一个值"活不够长".这个错误是什么意思?

lifetime rust borrow-checker

193
推荐指数
3
解决办法
2万
查看次数

如何在处理数据流时有效地构建向量和该向量的索引?

我有一个结构Foo:

struct Foo {
    v: String,
    // Other data not important for the question
}
Run Code Online (Sandbox Code Playgroud)

我想处理数据流并将结果保存到字段中Vec<Foo>,Vec<Foo>并在字段上为此创建索引Foo::v.

我想使用a HashMap<&str, usize>作为索引,其中键将是&Foo::v,而值是该位置Vec<Foo>,但我对其他建议持开放态度.

我想尽可能快地处理数据流,这需要两次不做明显的事情.

例如,我想:

  • String每个数据流读取只分配一次
  • 不要搜索索引两次,一次检查密钥不存在,一次用于插入新密钥.
  • 不使用Rc或增加运行时间RefCell.

借用检查器不允许此代码:

let mut l = Vec::<Foo>::new();
{
    let mut hash = HashMap::<&str, usize>::new();
    //here is loop in real code, like: 
    //let mut s: String; 
    //while get_s(&mut s) {
    let s = "aaa".to_string();
    let idx: usize = match hash.entry(&s) …
Run Code Online (Sandbox Code Playgroud)

lifetime move-semantics rust borrowing

7
推荐指数
3
解决办法
936
查看次数

有没有办法只在哈希集中查找类型被哈希的值?

我有一个结构,除其他数据外,还有一个唯一的id:

struct Foo {
    id: u32,
    other_data: u32,
}
Run Code Online (Sandbox Code Playgroud)

我想使用id键作为键并将其保留在结构中:

use std::collections::HashSet;
use std::hash::{Hash, Hasher};
impl PartialEq for Foo {
    fn eq(&self, other: &Foo) -> bool {
        self.id == other.id
    }
}
impl Eq for Foo {}
impl Hash for Foo {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.id.hash(state);
    }
}
Run Code Online (Sandbox Code Playgroud)

这有效:

pub fn bar() {
    let mut baz: HashSet<Foo> = HashSet::new();
    baz.insert(Foo {
        id: 1,
        other_data: 2,
    });
    let other_data = baz.get(&Foo {
        id: …
Run Code Online (Sandbox Code Playgroud)

hashmap hashset rust

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