最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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 Improve this question edited Jan 31 at 19:32 kmdreko 60.8k6 gold badges94 silver badges162 bronze badges asked Jan 30 at 6:42 HarryHarry 3,1601 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/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!(),
}
发布评论

评论列表(0)

  1. 暂无评论