Please first take a look at the code below.
struct Point<T> {
x: T,
}
impl<T> Point<T> {
fn get_x(&self) -> &T {
&self.x
}
}
fn main() {
let p = Point { x: 5 }; // Point<i32>
let x_value = p.get_x(); // &i32
println!("{}", x_value);
}
This code prints 5 and nothing seems surprising, but I was wondering why the type of x_value
has an &
in front of i32
. It seems redundant and if I change the line of println!("{}", x_value);
to println!("{}", *x_value);
, it also successfully prints 5. My question is, is there a preferred way when we have an option to return either referenced or dereferenced value?
I also would like you to check the following code.
struct Point<T> {
x: T,
}
impl<T> Point<T> {
fn get_x(&self) -> &T {
&self.x
}
}
fn main() {
let p = Point { x: "hello" }; // Point<&str>
let x_value = p.get_x(); // &&str
println!("{}", x_value);
}
The code is the same as the first one except the type of x_value
is now &&str
and it prints hello. I can dereference x_value
and the type of x_value
becomes &str
, and it also prints hello. Same question. Should I care about dereferencing x_value
and get &str
instead of getting &&str
? Is there a performance gain or some kind of benefit for choosing over the other one?