Let’s consider the following function:

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:

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:

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:

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: