【问题标题】:How to have a function return a hash map owning a string?如何让函数返回拥有字符串的哈希映射?
【发布时间】:2021-06-20 04:26:31
【问题描述】:
use std::collections::BTreeMap;

#[derive(Debug)]
struct TestStruct {
    name: String,
    num: f64,
}

fn main() {
    let test_struct = TestStruct {name: "Test".to_string(), num: 0.42 };
    println!("{:?}", test_struct);
}


fn get_fields_as_map(test_struct: &TestStruct) ->  BTreeMap<&str, &str> {
    let mut field_map: BTreeMap<&str, &str> = BTreeMap::new();
    field_map.insert("name", &test_struct.name);
    field_map.insert("num", &test_struct.num.to_string());
    field_map
}

playground

这会产生错误:

error[E0515]: cannot return value referencing temporary value
  --> src/main.rs:19:5
   |
18 |     field_map.insert("num", &test_struct.num.to_string());
   |                              --------------------------- temporary value created here
19 |     field_map
   |     ^^^^^^^^^ returns a value referencing data owned by the current function

我认为这是有道理的。 to_string() 函数正在分配一个字符串,其生命周期就是函数的生命周期。我还没有弄清楚如何分配字符串,使其具有与BTreeMap 相同的生命周期。我尝试了几种不同的方法,但都没有成功,我觉得我错过了一些东西。我不完全了解所有权。

【问题讨论】:

  • 我不完全了解所有权。”——我发现最容易问自己“谁来决定何时释放分配? i>" 在这种情况下,字符串不应被解除分配,除非/有人将其从地图中删除并且不再使用它:因此地图应拥有该字符串(直到所有权转移给将其从地图中删除的人),而不仅仅是引用它。通过将&amp;... 插入到映射中,它只保存一个引用(对函数返回时删除的字符串,在映射中留下一个悬空指针)。

标签: rust ownership


【解决方案1】:

如果您让地图拥有其中的字符串而不是存储引用,则可以避免头痛。引用意味着生命周期,并且您发现很难构造具有所需生命周期的&amp;strs。

&amp;str 引用更改为拥有的Strings,生活很简单:

fn get_fields_as_map(test_struct: &TestStruct) ->  BTreeMap<String, String> {
    let mut field_map = BTreeMap::new();
    field_map.insert("name".to_owned(), test_struct.name.to_owned());
    field_map.insert("num".to_owned(), test_struct.num.to_string());
    field_map
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 2011-09-29
    相关资源
    最近更新 更多