rust - `single_use_lifetimes` 在函数中派生的结构上意味着什么以及如何解决它?
问题描述
#![warn(single_use_lifetimes)]
fn do_foo() {
#[derive(Debug)]
struct Foo<'a> {
bar: &'a u32,
}
}
导致此警告:
warning: lifetime parameter `'a` only used once
--> src/lib.rs:6:16
|
6 | struct Foo<'a> {
| ^^
|
这个警告是什么意思?如何解决?
省略派生或函数时不会显示此警告。
解决方案
目的是防止这样的代码,其中生命周期是没有意义的明确指定:
pub fn example<'a>(_val: SomeType<'a>) {}
相反,最好使用'_
:
pub fn example(_val: SomeType<'_>) {}
如果你扩展你的代码并把它修剪下来,你会得到:
use std::fmt;
struct Foo<'a> {
bar: &'a u32,
}
impl<'a> fmt::Debug for Foo<'a> {
fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { Ok(()) }
}
warning: lifetime parameter `'a` only used once
--> src/lib.rs:9:6
|
9 | impl<'a> fmt::Debug for Foo<'a> {
| ^^
|
也就是说,<'a>
不需要,但派生无论如何都会添加它(因为自动生成代码很困难)。
老实说,我不知道这里的代码会发生什么变化,因为你不能'_
在那里使用结构的通用生命周期......
如何解决?
我不知道它是否可以,无需重写derive
.Debug
也可以看看:
推荐阅读
- c++ - 在 C++ 中使用 Go
- html - 类属性名称具体叫什么?
- javascript - 如何在Press上检索点击的图像反应原生
- node.js - Heroku 错误:ENOENT:没有这样的文件或目录,stat '/app/index.html'
- php - 添加 php.ini 文件后 my_phpinfo.php 为空
- kubernetes - 什么是 Kubernetes 中的负载均衡器,像 GKE 这样不同的 Kubernetes 引擎如何拥有自己的负载均衡器
- php - 尝试全局安装软件包时的 Composer 问题
- javascript - 在 Elementor 的 Fullpage JS 中添加水平幻灯片之间的过渡效果
- android - iOS 到 Android 加密
- ios - handleInputModeList 识别 touchUpInside 事件