Option.map vs Option.as_ref().map for primitives

Hi all,
I'm learning Rust and I'm writing some code for a project.
I have an Option and I need to create a new one that carries the sqtr of the first one.
Here is a very simple test case:

#[test]
fn test_map_option() {
    let opt1=Some(25_f64);
    let opt2=opt1.map(|v| v.sqrt());
    let opt3=opt1.as_ref().map(|v| v.sqrt());
    assert_eq!(25_f64,opt1.unwrap());
    assert_eq!(5.0_f64,opt2.unwrap());
    assert_eq!(5.0_f64,opt3.unwrap());
}

Provided that using opt1.map and opt1.as_ref().map yields the same result which one is better/more idiomatic?
My first guess is opt1.as_ref().map is better because it's more general (it works when the "object" inside Option is not Copy), but I'd like to hear what more experienced people suggest.

Thank you

just use whatever you are used to. for example, if you are just dealing with integers, there's no need to be "more general".

don't be obsessed with being "general". it's like obsession with "design patterns", you use it when you need it, not that you should use it everywhere because it is "more flexible" or "more encapsulated".

on the other hand, if you are in a generic context, the compiler will tell you if you are using the wrong one. so it's not something you should bother anyway.

2 Likes

Typically, you should avoid taking references to primitives just for the sake of it. It's more cognitive overhead and never even faster. Operate on primitives by value by default, unless you have a very good reason not to.

2 Likes

Thank you all, I'll avoid using as_ref for primitives.