[英]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.