I am trying to print some data for debugging purposes when I encountered an error. You can have a look at the full code here.
The error occurred when I tried to print data returned from the prepare_hash_data()
function, which returns a Vec<u8>
.
let data = self.prepare_hash_data()?; // returns Vec<u8>
println!("{}", String::from_utf8(data)?); // error here
let mut hasher = Sha256::new();
hasher.input(&data[..]);
println!("{}", hasher.result_str().as_str());
self.hash = hasher.result_str();
The prepare_hash_data()
function is given below. Other details are omitted. Simply, it is just a function that returns Vec<u8>
fn prepare_hash_data(&self) -> Result<Vec<u8>, failure::Error> {
let content = (
self.hash_prev_block.clone(),
self.transactions.clone(),
self.timestamp,
DIFFICULTY,
self.nonce
);
let bytes = bincode::serialize(&content)?;
Ok(bytes)
}
The error given is
error[E0382]: borrow of moved value: `data`
--> src/block.rs:63:23
|
60 | let data = self.prepare_hash_data()?;
| ---- move occurs because `data` has type `Vec<u8>`, which does not implement the `Copy` trait
61 | println!("{}", String::from_utf8(data)?);
| ---- value moved here
62 | let mut hasher = Sha256::new();
63 | hasher.input(&data[..]);
| ^^^^ value borrowed here after move
I tried the following ways
Implementing
Copy
trait. But,Vec<u8>
can't have theCopy
trait as described here.Looking at E0382 given in the error message, there are two ways suggested.
Using a
reference
, we can let another function borrow the value without changing its ownership.- But how should I use
reference
in this example? - Should I change the function signature to something like this
fn prepare_hash_data(&self) -> Result<&Vec<u8>, failure::Error>
?
- But how should I use
With
Rc
, a value cannot be owned by more than one variable.- Don't know how to implement.
I tried cloning the data by
println!("{}", String::from_utf8(data.clone())?);
- But, it gives another error
backtrace::backtrace::trace_unsynchronized
- For the full error log, click here
- But, it gives another error
What should be the correct approach to printing some data that can't be copied
or cloned
without moving
it for later usage in subsequent lines?
I did look at the following solutions but can't relate the answer.