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?
1 Answer
Reset to default 2This 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!(),
}
&Option<T>
in the first place, butOption<&T>
if T is not cheaply clonable, whichi32
is (it even isCopy
). Hence you should just return aOption<i32>
in the above case. youtube/watch?v=6c7pZYP_iIE – Richard Neumann Commented Jan 30 at 7:32