更新至Rust 1.18汇编:E0034范围内的多个适用项目;克隆到;
我有一段简单的代码,它使用了一个竞技场来分配内存,还有一个trait更新至Rust 1.18汇编:E0034范围内的多个适用项目;克隆到;,rust,Rust,我有一段简单的代码,它使用了一个竞技场来分配内存,还有一个traitCloneInto,其目的是将一个结构从未知的来源克隆到一个arena,同时调整生命周期: struct Arena; impl Arena { fn insert<'a, T: 'a>(&'a self, _: T) -> &'a mut T { unimplemented!() } } trait CloneInto<'a> { type Output: 'a
CloneInto
,其目的是将一个结构从未知的来源克隆到一个arena
,同时调整生命周期:
struct Arena;
impl Arena {
fn insert<'a, T: 'a>(&'a self, _: T) -> &'a mut T { unimplemented!() }
}
trait CloneInto<'a> {
type Output: 'a;
fn clone_into(&self, arena: &'a Arena) -> Self::Output;
}
struct-Arena;
impl竞技场{
fn insert(&'a self,:T)->&'a mut T T{unimplemented!()}
}
性状克隆体{a:&'a usize}
植入克隆{
类型输出=简单`
--> :18:5
|
18 |/fn clone_into(&self,arena:&'target arena)->Simple这是方法解析在Rust中工作的不幸结果。与其他具有重载特性的语言不同,在Rust中,要调用的确切函数必须明确解析,而不考虑其参数
在这种特定情况下,Rust 1.18带来了一种新的夜间方法,称为ToOwned
特征,并且ToOwned
特征无条件地为实现克隆的所有类型实现,并自动导入(通过)
无法在stable上调用此方法的事实与此无关;首先考虑使用此方法进行解析,如果实际使用此方法,将发出错误
请注意,尽管令人厌烦,但这种解决方法也有好处:人们往往不清楚当几个过载出现时,选择了哪个过载,或者为什么没有选择预期的过载。由于在明确性方面犯了错误,生锈使其成为一种不假思索的问题
不幸的是,在这种情况下,这会导致Simple::clone_into()
变得模棱两可
无法选择退出ToOwned
实现(必须放弃Clone
和Copy
),因此必须使用以下方法切换到对Clone\u的明确调用:
ToOwned
在中,所以是的,您正在导入它!@FrancisGagné:说得好。否则不会引起冲突。
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Eq, Ord, Hash)]
struct Simple<'a> { a: &'a usize }
impl<'a, 'target> CloneInto<'target> for Simple<'a> {
type Output = Simple<'target>;
fn clone_into(&self, arena: &'target Arena) -> Simple<'target> {
Simple { a: arena.insert(*self.a) }
}
}
fn main() {
let arena = Arena;
let _ = Simple { a: &1 }.clone_into(&arena);
}
error[E0034]: multiple applicable items in scope
--> <anon>:25:30
|
25 | let _ = Simple { a: &1 }.clone_into(&arena);
| ^^^^^^^^^^ multiple `clone_into` found
|
note: candidate #1 is defined in an impl of the trait `CloneInto` for the type `Simple<'_>`
--> <anon>:18:5
|
18 | / fn clone_into(&self, arena: &'target Arena) -> Simple<'target> {
19 | | Simple { a: arena.insert(*self.a) }
20 | | }
| |_____^
= note: candidate #2 is defined in an impl of the trait `std::borrow::ToOwned` for the type `_`
fn main() {
let arena = Arena;
let _ = CloneInto::clone_into(&Simple { a: &1 }, &arena);
}