Is it more conventional to pass-by-value or pass-by-reference when the method needs ownership of the value?

北慕城南 提交于 2020-11-26 13:28:31

问题


When I'm passing a object by reference to a struct's new() method, and the struct will own the object, is it more conventional to:

  • pass the object by reference, and do to_owned() in the new()
  • clone the object before calling new(), and pass by value, moving it

I can think of pros and cons of each in terms of clarity and separation-of-concerns.

#[derive(Clone)]
struct MyState;

struct MyStruct {
    state: MyState,
}

impl MyStruct {
    pub fn new_by_ref(state: &MyState) -> Self {
        MyStruct {
            state: state.to_owned(),
        }
    }

    pub fn new_by_val(state: MyState) -> Self {
        MyStruct { state }
    }
}

fn main() {
    let state1 = MyState;
    let struct1 = MyStruct::new_by_ref(&state1);

    let state2 = MyState;
    let struct2 = MyStruct::new_by_val(state2.clone());
}

回答1:


Pass by value.

This way, the program can avoid unnecessarily doubly-allocating the value if the caller no longer needs it.


In many cases, I recommend accepting anything that can be made into the owned type. This is easily demonstrated with String:

struct MyStruct {
    state: String,
}

impl MyStruct {
    fn new(state: impl Into<String>) -> Self {
        let state = state.into();
        MyStruct { state }
    }
}

fn main() {
    let struct1 = MyStruct::new("foo");
    let struct2 = MyStruct::new(String::from("bar"));
}

See also:

  • How to accept str, String and &String in a single rust function


来源:https://stackoverflow.com/questions/61898884/is-it-more-conventional-to-pass-by-value-or-pass-by-reference-when-the-method-ne

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!