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.self
or 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 &str
rather than &String
. Returning &String
requires a double de-reference to access the actual string contents, while returning &str
returns a fat pointer - a pointer to the string contents and the length - so the double de-reference is not needed.