rust - Why do I not need .as_ref() to match on a &Option<T> type? - Stack Overflow

admin2025-04-18  3

The below code works (getting same output) without the usage of as_ref().

struct A {
    a: Option<i32>,
}

impl A {
    fn new(a: i32) -> A {
        A {
            a: Some(a),
        }    
    }
    
    fn get_opt_ref(&self) -> &Option<i32> {
        &self.a
    }
}

fn main() {
    let a_obj = A::new(23);
    let a = match a_obj.get_opt_ref() /* a_obj.get_opt_ref().as_ref() */ {
        Some(a) => a,
        None => panic!(),
    };
    
    println!("{}", *a);
}

Does it make sense to use as_ref() method on &Option<> type?

The below code works (getting same output) without the usage of as_ref().

struct A {
    a: Option<i32>,
}

impl A {
    fn new(a: i32) -> A {
        A {
            a: Some(a),
        }    
    }
    
    fn get_opt_ref(&self) -> &Option<i32> {
        &self.a
    }
}

fn main() {
    let a_obj = A::new(23);
    let a = match a_obj.get_opt_ref() /* a_obj.get_opt_ref().as_ref() */ {
        Some(a) => a,
        None => panic!(),
    };
    
    println!("{}", *a);
}

Does it make sense to use as_ref() method on &Option<> type?

Share edited Jan 31 at 19:32 kmdreko 61.8k6 gold badges95 silver badges163 bronze badges asked Jan 30 at 6:42 HarryHarry 3,2681 gold badge24 silver badges46 bronze badges 1
  • 2 You shouldn't be using &Option<T> in the first place, but Option<&T> if T is not cheaply clonable, which i32 is (it even is Copy). Hence you should just return a Option<i32> in the above case. youtube.com/watch?v=6c7pZYP_iIE – Richard Neumann Commented Jan 30 at 7:32
Add a comment  | 

1 Answer 1

Reset to default 2

This is thanks to match ergonomics. In older Rust versions you would have needed either as_ref or to write:

match a_obj.get_opt_ref() {
   &Some (ref a) => todo!(),
   &None => todo!(),
}
转载请注明原文地址:http://anycun.com/QandA/1744934385a89695.html