繁体   English   中英

为什么 Rust 的 Add trait 拥有所有权?

[英]why does Rust's Add trait take ownership?

我正在写一个玩具 BigInt class,当我实现Add trait时,我注意到它拥有双方的所有权。 试图解决什么问题,而不是通过引用借用它们? 由于我使用Vec作为底层数据结构,我无法实现Copy ,这使得使用起来有些麻烦。

它导致的(轻微)不便的示例:

let i = BigInt::new();
//  - move occurs because `i` has type `BigInt`, which does not implement the `Copy` trait
let j = i + 16u32;
//      --------- `i` moved due to usage in operator
let k = i + 32u32;
//      ^ value used here after move

同样,我知道我可以只使用.clone() ,但我很好奇这在哪些方面帮助了程序员。

为什么能够取得所有权很重要的一个例子是String + &str可以 append 到现有字符串,而不是先克隆它。

您始终可以在其中实现Add for references 和.clone

struct A;

impl std::ops::Add for A {
    // normal impl
}

impl<'a> std::ops::Add for &'a A {
    // clone and delegate
}


fn main() {
    A + A; // This still compiles
    &A + &A; // This now compiles
    &A + A; A + &A; // These won't compile, but you can add those impls too, if you'd like

}

但是,您可能应该只对Copy类型执行此操作,以避免用户对隐藏的分配感到惊讶。

对于Copy类型,您可能需要 4 个 impl 才能将值添加到引用和对值的引用,如下所示:

impl std::ops::Add<T> for T;
impl<'a> std::ops::Add<T> for &'a T;
impl<'a> std::ops::Add<&'a T> for T;
impl<'a, 'b> std::ops::Add<&'a T> for &'b T; // Not sure if two lifetimes are needed here, but shouldn't hurt

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM