惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

I
InfoQ
博客园 - 司徒正美
爱范儿
爱范儿
F
Fortinet All Blogs
J
Java Code Geeks
量子位
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 三生石上(FineUI控件)
腾讯CDC
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
S
SegmentFault 最新的问题
Microsoft Security Blog
Microsoft Security Blog
T
The Blog of Author Tim Ferriss
V
V2EX
L
LangChain Blog
aimingoo的专栏
aimingoo的专栏
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
云风的 BLOG
云风的 BLOG
T
Tailwind CSS Blog
Blog — PlanetScale
Blog — PlanetScale
GbyAI
GbyAI
A
About on SuperTechFans
有赞技术团队
有赞技术团队
Y
Y Combinator Blog

hsfzxjy 的博客

解决 VSCode + CMake + MSVC 编译器信息乱码的问题 使用 3090 部署 1.58bit 动态量化版 DeepSeek R1 671b 如何在 VS Code DevContainer 中配置 HTTP 代理 如何在跳板机背后的服务器上使用 VS Code Remote - Containers Cohesive Digests for Ints and Floats Rust 中的隐匿概念 —— Place(位置) 美术馆 一尺之槌,日取其半,1075日而竭 老生常谈:使用 Cloudflare 自选 IP 加速站点访问 辩义 State、Nation 与 Country 将 Base64 编码的数据快速转换为 Uint8Array 折腾 NPU·第1章 —— 搭建 Level Zero 开发环境 折腾 NPU·第0章 —— Intel NPU 概述与 Level-Zero 新增域名 monad.run CSS 中为特定字符设置不同字体 Arbitary Lifetime Transmutation via Rust Unsoundness Dijkstra 算法的延伸 Manacher 回文计数算法 硬卧 Go Fact: Zero-sized Field at the Rear of a Struct Has Non-zero Size Display *big.Rat Losslessly and Smartly in Golang 代码的仪式 Building Electron From Scratch 中式亲属称谓研究之一:构建半群 Some Notes on Kotlin Coroutines Git sparse-checkout and partial clones for Mega-Repos 辩义“封建” Diving from the CUDA Error 804 into a bug of libnvidia-container Modern Cryptography, GPG and Integration with Git(hub) Move the Root Partition of Ubuntu
Option::as_ref
2019-06-26 · via hsfzxjy 的博客

Let’s consider the following function:

use std::ptr::NonNull;

fn transform<T>(option: &Option<NonNull<T>>) -> Option<&T> {
option.map(|x| unsafe { x.as_ref() })
}

The function transform takes an Option<NonNull<T>> as input, and converts the inner pointer to an immutable reference &T if possible. The method NonNull::as_ref() is marked unsafe so we need an unsafe block. The snippet causes an compilation error:

error[E0515]: cannot return value referencing function parameter `x`
--> src/main.rs:6:29
|
6 | option.map(|x| unsafe { x.as_ref() })
| -^^^^^^^^^
| |
| returns a value referencing data owned by the current function
| `x` is borrowed here

This is a common mistake when transforming Option s. To figure out the problem, we may try to take apart the signature and see how the value flows:

fn Option::map<T, F>(self, f: F) -> Option<&T>
where F: FnOnce(NonNull<T>) -> Option<&T>
{}



fn __closure<T>(x: NonNull<T>) -> &T {}

unsafe fn NonNull::as_ref<T, 'a>(&'a self) -> &'a T {}

where __closure denotes the closure Option::map takes.

Note that Option::map is a self-consuming method. During the calling, option is destructed, and the internal value with type NonNull<T> flows into __closure . The closure, however, consumes its argument as well. Consequently x would have a lifetime trapped in the closure. This is what “data owned by the current function” in the error message means.

Now take a look into the closure. Inside we call NonNull::as_ref() to convert a pointer into a reference, which assumes the pointer should live as long as the reference returned. However, the implication could not be satisfied, since x the pointer lives only within the closure, but the reference would be passed out of the closure. The compiler complains for the lifetime mismatch.

One can always employ Option::as_ref() as a solution. The function has a signature as below:

fn Option::as_ref<T>(&self) -> Option<&T> {}

Calling .as_ref() on an Option<T> instance, say x , will return another Option with type Option<&T> , say ref_x , which holds the reference to the inner value of x . It’s worth noting that .as_ref() takes x by reference, so no consuming happens here. Now we can perform .map() or .unwrap() on ref_x to extract the internal &T , and call non-consuming methods on it (e.g., NonNull::as_ref ). ref_x will still be dropped after that, but it does not matter, since all it have is a reference.

We can correct our code like this:

fn transform<T>(option: &Option<NonNull<T>>) -> Option<&T> {
option
.as_ref()
.map(|x| unsafe { x.as_ref() })
}

Author: hsfzxjy.
Link: .
License: CC BY-NC-ND 4.0.
All rights reserved by the author.
Commercial use of this post in any form is NOT permitted.
Non-commercial use of this post should be attributed with this block of text.