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());
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…