Given this struct:
struct TestS {
astr: String,
}
impl TestS {
pub fn new(s: String) -> Self { Self{ astr: s } }
pub fn get_ref(&self) -> &String { &self.astr }
pub fn get_val(&self) -> String { self.astr.clone() }
}
Are there any downsides to returning the reference versus returning the value? I like returning the reference because it avoids making a potentially unnecessary copy. The Rust compiler should prevent the dangling reference. The caller can make a copy if needed. Is this correct?
As a rule of thumb:
Copy, then return it by value.selfor has perhaps created the value locally) then return it by valueIf cloning is required, it should be done at the place where the owned value is needed (so the caller in your example).
As per @vallentin's comment, for a String you would usually return
&strrather than&String. Returning&Stringrequires a double de-reference to access the actual string contents, while returning&strreturns a fat pointer - a pointer to the string contents and the length - so the double de-reference is not needed.