gpt4 book ai didi

rust - 从循环内部向外部范围内的容器存储借来的值?

转载 作者:行者123 更新时间:2023-11-29 08:33:25 26 4
gpt4 key购买 nike

我给自己设定了一个小任务来获取一些基本的 Rust 知识。任务是:

Read some key-value pairs from stdin and put them into a hashmap.

然而,事实证明这是一个比预期更棘手的挑战。主要是由于对生命周期的理解。下面的代码是我经过几次实验后得到的,但编译器一直在对我大喊大叫。

use std::io;
use std::collections::HashMap;

fn main() {
let mut input = io::stdin();
let mut lock = input.lock();
let mut lines_iter = lock.lines();

let mut map = HashMap::new();

for line in lines_iter {
let text = line.ok().unwrap();
let kv_pair: Vec<&str> = text.words().take(2).collect();

map.insert(kv_pair[0], kv_pair[1]);
}

println!("{}", map.len());
}

编译器基本上说:

`text` does not live long enough

据我了解,这是因为“文本”的生命周期仅限于循环范围。因此,我在循环中提取的键值对也绑定(bind)到循环边界。因此,将它们插入外部 map 会导致悬空指针,因为“文本”将在每次迭代后被销毁。 (如果我错了请告诉我)

最大的问题是:如何解决这个问题?

我的直觉是:

制作键值对的“拥有副本”并将其生命周期“扩展”到外部范围....但我不知道如何实现这一点。

最佳答案

The lifetime of 'text' is limited to the scope of the loop. The key-value pair that I'm extracting within the loop is therefore also bound to the loops boundaries. Thus, inserting them to the outer map would lead to an dangling pointer since 'text' will be destroyed after each iteration.

我觉得不错。

Make an "owned copy" of the key value pair.

拥有的&str是一个String:

map.insert(kv_pair[0].to_string(), kv_pair[1].to_string());

编辑

原始代码在下面,但我更新了上面的答案以使其更加地道

map.insert(String::from_str(kv_pair[0]), String::from_str(kv_pair[1]));

关于rust - 从循环内部向外部范围内的容器存储借来的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39873206/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com