对于实现Clone
的任意结构,我希望有一个通用函数可以采用:
&MyStruct
在这种情况下,可以通过函数MyStruct
,在这种情况下克隆是不必要的,因为它可以被移动我自己实现了这个:
use std::clone::Clone;
#[derive(Debug)]
struct MyStruct {
value: u64,
}
impl Clone for MyStruct {
fn clone(&self) -> Self {
println!("cloning {:?}", self);
MyStruct { value: self.value }
}
}
trait TraitInQuestion<T> {
fn clone_or_no_op(self) -> T;
}
impl TraitInQuestion<MyStruct> for MyStruct {
fn clone_or_no_op(self) -> MyStruct {
self
}
}
impl<'a> TraitInQuestion<MyStruct> for &'a MyStruct {
fn clone_or_no_op(self) -> MyStruct {
self.clone()
}
}
fn test<T: TraitInQuestion<MyStruct>>(t: T) {
let owned = t.clone_or_no_op();
}
fn main() {
let a = MyStruct { value: 8675309 };
println!("borrowing to be cloned");
test(&a);
println!("moving");
test(a);
}
并且输出符合预期:
borrowing to be cloned
cloning MyStruct { value: 8675309 }
moving
是否已通过实施Clone
以某种方式推导出此功能?如果没有,std::borrow::ToOwned
听起来就像我想要的那样,但我无法让它发挥作用:
use std::clone::Clone;
use std::borrow::Borrow;
#[derive(Debug)]
struct MyStruct {
value: u64,
}
impl Clone for MyStruct {
fn clone(&self) -> Self {
println!("cloning {:?}", self);
MyStruct { value: self.value }
}
}
fn test<T: ToOwned<Owned = MyStruct>>(a: T) {
let owned = a.to_owned();
}
fn main() {
let a = MyStruct { value: 8675309 };
println!("borrowing to be cloned");
test(&a);
println!("moving");
test(a);
}
编译器输出:
error[E0277]: the trait bound `MyStruct: std::borrow::Borrow<T>` is not satisfied
--> src/main.rs:16:1
|
16 | / fn test<T: ToOwned<Owned = MyStruct>>(a: T) {
17 | | let owned = a.to_owned();
18 | | }
| |_^ the trait `std::borrow::Borrow<T>` is not implemented for `MyStruct`
|
= help: consider adding a `where MyStruct: std::borrow::Borrow<T>` bound
= note: required by `std::borrow::ToOwned`
通过更改test
:
fn test<T: ToOwned<Owned = MyStruct>>(a: T) -> ()
where
MyStruct: Borrow<T>,
{
let owned = a.to_owned();
}
结果错误:
error[E0308]: mismatched types
--> src/main.rs:27:10
|
27 | test(&a);
| ^^ expected struct `MyStruct`, found &MyStruct
|
= note: expected type `MyStruct`
found type `&MyStruct`
如果我尝试为ToOwned
&MyStruct
impl<'a> ToOwned for &'a MyStruct {
type Owned = MyStruct;
fn to_owned(&self) -> Self::Owned {
self.clone()
}
}
我收到以下错误:
error[E0119]: conflicting implementations of trait `std::borrow::ToOwned` for type `&MyStruct`:
--> src/main.rs:16:1
|
16 | / impl<'a> ToOwned for &'a MyStruct {
17 | | type Owned = MyStruct;
18 | |
19 | | fn to_owned(&self) -> Self::Owned {
20 | | self.clone()
21 | | }
22 | | }
| |_^
|
= note: conflicting implementation in crate `alloc`
答案 0 :(得分:2)
@Shepmaster指出有Cow
;但是您需要手动创建Cow::Borrowed(&a)
或Cow::Owned(a)
个实例,并且包装的(Owned
)类型必须始终实现Clone
(对于T: ToOwned<Owned=T>
)。
(Clone
ToOwned::Owned
对于自定义ToOwned
实施可能并非绝对必要;但.borrow().to_owned()
的作用类似于.clone()
,因此没有理由隐藏它。)
虽然您应该使用通用实现,但您自己的特性是替代方案的良好开端。这样,只要您没有传递引用,就不需要类型来实现Clone
:
trait CloneOrNoOp<T> {
fn clone_or_no_op(self) -> T;
}
impl<T> CloneOrNoOp<T> for T {
fn clone_or_no_op(self) -> T {
self
}
}
impl<'a, T: Clone> CloneOrNoOp<T> for &'a T {
fn clone_or_no_op(self) -> T {
self.clone()
}
}
struct MyStructNoClone;
#[derive(Debug)]
struct MyStruct {
value: u64,
}
impl Clone for MyStruct {
fn clone(&self) -> Self {
println!("cloning {:?}", self);
MyStruct { value: self.value }
}
}
fn test<T: CloneOrNoOp<MyStruct>>(t: T) {
let _owned = t.clone_or_no_op();
}
// if `I` implement `Clone` this takes either `&I` or `I`; if `I` doesn't
// implement `Clone` it still will accept `I` (but not `&I`).
fn test2<I, T: CloneOrNoOp<I>>(t: T) {
let _owned: I = t.clone_or_no_op();
}
fn main() {
let a = MyStruct { value: 8675309 };
println!("borrowing to be cloned");
test(&a);
// cannot infer `I`, could be `&MyStruct` or `MyStruct`:
// test2(&a);
test2::<MyStruct,_>(&a);
test2::<&MyStruct,_>(&a);
println!("moving");
test(a);
let a = MyStructNoClone;
test2(&a);
// the previous line is inferred as ("cloning" the reference):
test2::<&MyStructNoClone,_>(&a);
// not going to work (because it can't clone):
// test2::<MyStructNoClone,_>(&a);
test2(a);
}
可悲的是,现在似乎无法将CloneOrNoOp
基于ToOwned
(而非Clone
),如下所示:
impl<'a, B> CloneOrNoOp<B::Owned> for &'a B
where
B: ToOwned,
{
fn clone_or_no_op(self) -> B::Owned {
self.to_owned()
}
}
编译器看到“CloneOrNoOp<&_>
类型&_
”的冲突实现(某人疯狂可能会实现ToOwned for Foo { type Owned = &'static Foo; ... }
;特征无法根据生命周期差异区分实现。)
但与ToOwned
类似,您可以实施特定的自定义,例如:
impl<'a> CloneOrNoOp<String> for &'a str {
fn clone_or_no_op(self) -> String {
self.to_owned()
}
}
现在,如果您想获得&str
,则可以传递&String
,String
或String
中的任何一个:
test2::<String,_>("abc");
test2::<String,_>(&String::from("abc"));
test2::<String,_>(String::from("abc"));