从循环内部将借用值存储到外部作用域中的容器? [英] Storing from inside a loop a borrowed value to container in outer scope?

查看:33
本文介绍了从循环内部将借用值存储到外部作用域中的容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我给自己设置了一个小任务来获得一些基本的 Rust 知识.任务是:

I set myself a little task to acquire some basic Rust knowledge. The task was:

从标准输入中读取一些键值对并将它们放入一个哈希映射中.

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

然而,结果证明这是一个比预期更棘手的挑战.主要是因为对生命周期的理解.以下代码是我经过几次实验后目前拥有的代码,但编译器并没有停止对我大喊大叫.

This, however, turned out to be a trickier challenge than expected. Mainly due to the understanding of lifetimes. The following code is what I currently have after a few experiments, but the compiler just doesn't stop yelling at me.

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

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

As far as I understand, this is because 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 a dangling pointer since 'text' will be destroyed after each iteration. (Please tell me if I'm wrong)

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

The big question is: How to solve this issue?

我的直觉是:

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

Make an "owned copy" of the key value pair and "expand" it's lifetime to the outer scope .... but I have no idea how to achieve this.

推荐答案

'text' 的生命周期仅限于循环的范围.因此,我在循环中提取的键值对也绑定到循环边界.因此,将它们插入外部映射会导致悬空指针,因为每次迭代后文本"都会被销毁.

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:

An owned &str is a String:

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

编辑

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

The original code is below, but I've updated the answer above to be more idiomatic

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

这篇关于从循环内部将借用值存储到外部作用域中的容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆