How To Fix - Use of Moved Value Error in Rust ?
In this post, we will explore How To Fix - "Use of Moved Value" Error in Rust. Sample error
error\[E0352\]: use of moved value: 'xxxx'
\- value moved here
^ value used here after move
Solution 1 :
- Use Clone - One way would be to use Clone. Clone is a trait used to create a duplicate object. Then you pass this duplicate. That way don't actually pass the owned value - rather a duplicate copy.
- Clone differs from Copy. Because Copy is implicit & inexpensive bit-wise copy. Whereas Clone is explicit and can be expensive or in-expensive.
- In Rust, we can not re-implement Copy. However we can re-implement Clone to run any arbitrary code.
- As such Clone is more general than Copy. So you can automatically make anything Copy to be be Clone as well.
pub trait Clone {
fn clone(&self) -> Self;
fn clone\_from(&mut self, source: &Self) { ... }
}
- You can also make it "Derivable" by using #[derive] if all fields are Clone. Such a derived implementation of Clone would call the clone on every field.
For any generic struct, #[derive] implements Clone conditionally by adding bound Clone on generic parameters.
// \`derive\` implements Clone for Reading<T> when T is Clone.
#\[derive(Clone)\]
struct Reading<T> {
frequency: T,
}
- To implement Clone, by default, Types that are Copy should have an implementation of Clone.
If
T: Copy,
x: T, and
y: &T, then
let x = y.clone(); is equivalent to let x = *y;
struct Generate<T>(fn() -> T);
impl<T> Copy for Generate<T> {}
impl<T> Clone for Generate<T> {
fn clone(&self) -> Self {
\*self
}
}
Types that are Copy should have a trivial implementation of Clone. More formally: if T: Copy, x: T, and y: &T, then let x = y.clone(); is equivalent to let x = *y;. Manual implementations should be careful to uphold this invariant; however, unsafe code must not rely on it to ensure memory safety.
Solution 2 :
- Use Borrow - Instead of moving it, borrow the Vector that you're iterating over .
- Sometimes it is quite inconvenient to pass the ownership of a variable to another function and then return back the ownership. As such Rust has a concept called - borrowing. In borrowing, the ownership of a value is transferred temporarily to an entity and then returned back to the original owner entity.
e.g. when a function transfers it's control of a variable to another function temporarily, for a while, it is called borrowing. This can be achieved by passing a reference to the variable (& variable-name) instead of passing the variable itself to the function. That way the ownership of the variable is transferred back to the original owner upon the function (to which the control was passed) completes execution.
fn main(){
let a = vec!\[1,2,3,4,5,6,7,8,9,0\];
sub\_func(&a); //<--- reference is passed not the variable
println!("Passed from main() v\[0\]={}",v\[0\]);
}
fn sub\_func(x:&Vec<i32>){
println!("sub\_func {:?}",x);
}
Hope this helps to fix the issue.
Other Interesting Reads - · How to Send Large Messages in Kafka ? · Fix Spark Error – “org.apache.spark.SparkException: Failed to get broadcast_0_piece0 of broadcast_0” · How to Handle Bad or Corrupt records in Apache Spark ? · How to use Broadcast Variable in Spark ? · How to log an error in Python ? · How to Code Custom Exception Handling in Python ? · How to Handle Errors and Exceptions in Python ? · How To Fix – “Ssl: Certificate_Verify_Failed” Error in Python ? · How to Send Large Messages in Kafka ? · Fix Spark Error – “org.apache.spark.SparkException: Failed to get broadcast_0_piece0 of broadcast_0” · How to Handle Bad or Corrupt records in Apache Spark ? · How to use Broadcast Variable in Spark ? · Best Practices for Dependency Problem in Spark · Sample Code – Spark Structured Streaming vs Spark Streaming · Sample Code for PySpark Cassandra Application · How to Enable UTF-8 in Python ? · How to log an error in Python ? · Sample Python Code To Read & Write Various File Formats (JSON, XML, CSV, Text) · How to Handle Errors and Exceptions in Python ? · How to Handle Bad or Corrupt records in Apache Spark ? · How To Fix – Partitions Being Revoked and Reassigned issue in Kafka ? · What Are The Most Important Metrics to Monitor in Kafka ? · How To Connect Local Python to Kafka on AWS EC2 ? · How to Send Large Messages in Kafka ? · Fix Spark Error – “org.apache.spark.SparkException: Failed to get broadcast_0_piece0 of broadcast_0”
error\[E0352\]: use of moved value: 'xxxx' ,use of moved value: 'xxxx' ,use of moved value: ,- value moved here ,^ value used here after move ,rust use of moved value string ,borrow of moved value rust ,move occurs because value has type string, which does not implement the copy trait ,rust assignment to borrowed ,rust references explained ,rust value moved here ,move occurs because has type \`string\`, which does not implement the \`copy\` trait ,implement copy trait rust ,moved due to this method call ,rust string ,rust move ,borrow of moved value string ,value moved here, in previous iteration of loop rust ,rust move value ,rust force move ,rust move ownership ,rust borrow ,rust option move