Let’s consider the following function:

1
2
3
4
5
use std::ptr::NonNull;
fn transform<T>(option: &Option<NonNull<T>>) -> Option<&T> {
option.map(|x| unsafe { x.as_ref() })
}

The function transform takes in an Option<NonNull<T>> as input, and convert the inner pointer to immutable reference &T if available. The method NonNull::as_ref() is marked unsafe so we need an unsafe block. The snippet didn’t compile well however:

1
2
3
4
5
6
7
8
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 Options. To address the problem, we may try to write down the signatures of relevant functions and see how the values flow down:

1
2
3
4
5
6
7
8
9
fn Option::map<T, F>(self, f: F) -> Option<&T>
where F: FnOnce(NonNull<T>) -> Option<&T>
{}
// which implies:
fn __closure<T>(x: NonNull<T>) -> &T {}
unsafe fn NonNull::as_ref<T, 'a>(&'a self) -> &'a T {}

Here __closure denotes the closure Option::map takes.

Note that Option::map is a self-consuming method. During the calling, option is destructured, and the inner value with type NonNull<T> flows into __closure. The closure, however, consumes its parameter too, so finally x would have a lifetime limited in the closure. This is what data owned by the current function in the error message means.

Now let’s 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 returned reference. This could not be satisfied, since x the pointer only lives in the closure, but the reference would be passed out of the closure. Thus the compiler complains.

We can always use Option::as_ref() to solve this type of issues. The function has signature as below:

1
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 have 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 inner &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:

1
2
3
4
5
fn transform<T>(option: &Option<NonNull<T>>) -> Option<&T> {
option
.as_ref() // Note here
.map(|x| unsafe { x.as_ref() })
}