I need to use the bigdecimal
crate, so I include it in my dependencies in Cargo.toml
file:
[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
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). 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).
In other cases, you may need calls like val2.clone()
to make a copy explicitly.
For why BigDecimal
can't be Copy
(then it would make copies automatically whenever needed), see 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 implementCopy
, butBigInt
has aVec
underneath, so it can only be explicitly cloned.