Option<T> to Option<&T>


#1

Is it possible to get a reference from a Result (or any other wrapper really) of an owned value?

For example, this is an error:

let foo = Ok(String::from("foo"));
let foo_ref = foo.map(|s| &s);

The use case is I want to chain a bunch of calls together via and_then, and I can’t pass around an owned value because then it will be dropped prematurely in the case of returning an error

At least I think… haven’t thought it through 100% but playing around with some of this hasn’t brought me to a solution yet. Will followup Sunday most likely

Thanks!


#2

Well, you titled this Option, but your code shows a Result. If you’re serious about Option, you can go with as_ref to convert a &Option<T> to an Option<&T>.

let foo = Some(String::from("foo"));
let foo_ref:Option<&String> = (&foo).as_ref();

Seems this works for Result too, but this will “ref” the error as well, not sure that’s what you want.


#3

.as_ref() is what you’re looking for.


#4

Method call syntax auto refs, so you just need to write foo.as_ref(), this works for both Option and Result.