当方法需要值的所有权时,按值传递还是按引用传递更常规?

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

当我通过对结构的 new() 方法的引用传递一个对象时,该结构将拥有该对象,是否更常规:

我可以从清晰度和关注点分离的角度考虑各自的优缺点。

#[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());
}

按值传递。

这样,程序可以避免在调用者不再需要时不必要地重复分配值。


在许多情况下,我建议接受任何可以成为 into 拥有类型的东西。这很容易用 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"));
}

另请参阅: