当我通过引用结构体的new()方法传递对象,并且结构体将拥有该对象时,是否更传统:
to_owned()在new()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());
}
Run Code Online (Sandbox Code Playgroud)