相关疑难解决方法(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万
查看次数

如何返回对互斥锁下的值的子值的引用?

我有一个看起来像这样的结构:

pub struct MyStruct {
    data: Arc<Mutex<HashMap<i32, Vec<i32>>>>,
}
Run Code Online (Sandbox Code Playgroud)

我可以很容易地锁定互斥锁并查询底层HashMap:

let d = s.data.lock().unwrap();
let v = d.get(&1).unwrap();
println!("{:?}", v);
Run Code Online (Sandbox Code Playgroud)

现在我想创建一个封装查询的方法,所以我写了这样的东西:

impl MyStruct {
    pub fn get_data_for(&self, i: &i32) -> &Vec<i32> {
        let d = self.data.lock().unwrap();
        d.get(i).unwrap()
    }
}
Run Code Online (Sandbox Code Playgroud)

这无法编译,因为我试图在以下情况下返回对数据的引用Mutex:

error: `d` does not live long enough
  --> <anon>:30:9
   |
30 |         d.get(i).unwrap()
   |         ^
   |
note: reference must be valid for the anonymous lifetime #1 defined on the block at 28:53...
  --> <anon>:28:54
   |
28 …
Run Code Online (Sandbox Code Playgroud)

rust

15
推荐指数
4
解决办法
1493
查看次数

如何将 Chars 迭代器存储在与它正在迭代的 String 相同的结构中?

我刚刚开始学习 Rust,我正在努力处理生命周期。

我想要一个带有 a 的结构String,它将用于缓冲来自 stdin 的行。然后我想在结构上有一个方法,它从缓冲区返回下一个字符,或者如果该行中的所有字符都已被消耗,它将从标准输入读取下一行。

文档说 Rust 字符串不能按字符索引,因为 UTF-8 效率低下。当我按顺序访​​问字符时,使用迭代器应该没问题。但是,据我所知,Rust 中的迭代器与它们正在迭代的事物的生命周期相关联,我无法弄清楚如何将这个迭代器与String.

这是我想要实现的伪 Rust。显然它不会编译。

struct CharGetter {
    /* Buffer containing one line of input at a time */
    input_buf: String,
    /* The position within input_buf of the next character to
     * return. This needs a lifetime parameter. */
    input_pos: std::str::Chars
}

impl CharGetter {
    fn next(&mut self) -> Result<char, io::Error> {
        loop {
            match self.input_pos.next() {
                /* If there is still a character left in …
Run Code Online (Sandbox Code Playgroud)

rust

9
推荐指数
1
解决办法
2428
查看次数

标签 统计

rust ×3

borrow-checker ×1

lifetime ×1