“缺少生命周期说明符"是什么意思?在结构中存储 &str 是什么意思? [英] What does "missing lifetime specifier" mean when storing a &str in a structure?

查看:37
本文介绍了“缺少生命周期说明符"是什么意思?在结构中存储 &str 是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写类似 Excel 的数据结构:

I am trying to code an Excel-like data structure:

use std::collections::HashMap;

struct Excel {
    columns: HashMap<&str, Vec<f64>>,
}

fn main() {}

但我收到一个错误:

error[E0106]: missing lifetime specifier
 --> src/main.rs:4:22
  |
4 |     columns: HashMap<&str, Vec<f64>>,
  |                      ^ expected lifetime parameter

有人能帮我了解发生了什么吗?

Can someone help me understand what's going on?

推荐答案

缺少生命周期说明符"意味着在结构定义中,您没有告诉它对字符串切片的引用允许保留多长时间.为了让您的代码安全,它必须至少与结构体一样长.

"Missing lifetime specifier" means that in the struct definition, you haven't told it how long the reference to the string slice is allowed to stay around. In order for your code to be safe, it has to stick around for at least as long as the struct.

您需要在结构上定义生命周期参数并将其用于字符串切片.

You need to define a lifetime parameter on your struct and use it for the string slice.

struct Excel<'a> {
    columns: HashMap<&'a str, Vec<f64>>
}

这表示字符串切片(HashMap 键)具有一些由 Excel 结构的用户参数化的生命周期.生命周期是 Rust 的关键特性之一.您可以在 Rust 文档 中阅读有关生命周期的更多信息.

This says that string slice (the HashMap key) has some lifetime parameterized by the user of the Excel struct. Lifetimes are one of the key features of Rust. You can read more about lifetimes in Rust documentation.

通常定义一个拥有字符串的结构更简单.然后你可以使用String.

Usually it's simpler to define a struct that owns the string. Then you can use String.

struct Excel {
    columns: HashMap<String, Vec<f64>>
}

这篇关于“缺少生命周期说明符"是什么意思?在结构中存储 &amp;str 是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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