Search code examples
rustreferencelifetime

Any downsides to returning a reference to struct variable in Rust?


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?


Solution

  • As a rule of thumb:

    • If what you are returning is Copy, then return it by value.
    • If the function has local ownership of the value (for example, a method which has consumed self or has perhaps created the value locally) then return it by value
    • Otherwise, return a reference and allow the caller to clone it if they need an owned value

    If 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.