`bigdecimal::BigDecimal`,它没有实现 `Copy` 特性

`bigdecimal::BigDecimal`, which does not implement the `Copy` trait

我需要使用 bigdecimal 包,所以我将它包含在 Cargo.toml 文件的依赖项中:

[dependencies]
bigdecimal = "0.1.0"

在编写代码时,出现以下错误:

bigdecimal::BigDecimal, which does not implement the 'Copy' trait

例如:

use bigdecimal::BigDecimal;
use std::str::FromStr;

fn main() {
    let val_1 = BigDecimal::from_str("1").unwrap();
    let val_2 = BigDecimal::from_str("2").unwrap();

    let result = val_2/val_1;

    println!("Test 1 {} ", result);
    println!("Test 2 {} ", val_2);
}

执行时会出现如下错误信息:

----- move occurs because `val_2` has type `bigdecimal::BigDecimal`, which does not implement the `Copy` trait

我能解决它的唯一方法是在打印语句

之前再次声明val_2
println!("Test 1 {} ", result);
let val_2 = BigDecimal::from_str("2").unwrap();
println!("Test 2 {} ", val_2);

还有其他有效的方法可以解决吗?

这种情况下可以参考一下:

let result = &val_2/&val_1;

使用正确版本的除法:impl<'a, 'b> Div<&'b BigDecimal> for &'a BigDecimal 您的代码当前使用 impl Div<BigDecimal> for BigDecimal(您可以先在 https://docs.rs/bigdecimal/0.1.0/bigdecimal/struct.BigDecimal.html as well as many other versions). If the difference doesn't make sense to you, you really need to read References and Borrowing 中找到两者(以及 'a 'b部分现在可能可以忽略)。

在其他情况下,您可能需要像 val2.clone() 这样的调用来显式复制。

为什么 BigDecimal 不能是 Copy(然后它会在需要时自动制作副本),参见 https://github.com/rust-num/num/issues/191:

As a rule of thumb, only primitives and aggregates composed of just primitives can implement Copy. So for instance, PrimInt does implement Copy, but BigInt has a Vec underneath, so it can only be explicitly cloned.