[英]`bigdecimal::BigDecimal`, which does not implement the `Copy` trait
I need to use the bigdecimal
crate, so I include it in my dependencies in Cargo.toml
file:我需要使用
bigdecimal
crate,所以我将它包含在Cargo.toml
文件中的依赖项中:
[dependencies]
bigdecimal = "0.1.0"
While writing the code, I get the following error:在编写代码时,我收到以下错误:
bigdecimal::BigDecimal, which does not implement the 'Copy' trait
For example:例如:
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);
}
When execute the error message below will appear:执行时会出现以下错误信息:
----- move occurs because `val_2` has type `bigdecimal::BigDecimal`, which does not implement the `Copy` trait
The only way I can solve it is by declaring again val_2 before the print statement我可以解决它的唯一方法是在打印语句之前再次声明 val_2
println!("Test 1 {} ", result);
let val_2 = BigDecimal::from_str("2").unwrap();
println!("Test 2 {} ", val_2);
Is there any other efficient way to solve it?有没有其他有效的方法来解决它?
In this case you can just take references:在这种情况下,您可以参考:
let result = &val_2/&val_1;
to use the proper version of division: impl<'a, 'b> Div<&'b BigDecimal> for &'a BigDecimal
where your code currently uses impl Div<BigDecimal> for BigDecimal
(you can find both in https://docs.rs/bigdecimal/0.1.0/bigdecimal/struct.BigDecimal.html as well as many other versions).使用正确版本的除法:
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以及许多其他版本)。 If the difference doesn't make sense to you, you really need to read References and Borrowing first (and the 'a
'b
parts can probably be ignored for now).如果差异对您没有意义,您真的需要先阅读参考文献和借用书(现在可能可以忽略
'a
'b
部分)。
In other cases, you may need calls like val2.clone()
to make a copy explicitly.在其他情况下,您可能需要像
val2.clone()
这样的调用来显式地进行复制。
For why BigDecimal
can't be Copy
(then it would make copies automatically whenever needed), see https://github.com/rust-num/num/issues/191 :关于为什么
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
.根据经验,只有原语和仅由原语组成的聚合才能实现
Copy
。 So for instance,PrimInt
does implementCopy
, butBigInt
has aVec
underneath, so it can only be explicitly cloned.例如,
PrimInt
确实实现了Copy
,但BigInt
在下面有一个Vec
,所以它只能被显式克隆。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.