Rust中Vec<u8>所有权转移引发E0382错误的解决咨询
解决Rust中Vec所有权转移导致的E0382错误
调试时打印prepare_hash_data()返回的Vec<u8>数据后,后续使用data触发E0382错误,核心原因是String::from_utf8(data)会转移data的所有权,导致后续无法再借用data。
相关代码
出错的代码段:
let data = self.prepare_hash_data()?; // 返回Vec<u8> println!("{}", String::from_utf8(data)?); // 错误发生处 let mut hasher = Sha256::new(); hasher.input(&data[..]); println!("{}", hasher.result_str().as_str()); self.hash = hasher.result_str();
prepare_hash_data()函数定义:
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) }
报错信息
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
已尝试的方案
- 为
Vec<u8>实现Copytrait:不可行,Vec本身不支持Copy - 参考E0382文档的引用/Rc方案:不知如何落地
- 使用
data.clone():出现新错误
可行解决方案
方案1:使用引用式转换(推荐)
不需要转移data所有权,直接传入data的切片引用进行字符串转换:
let data = self.prepare_hash_data()?; // 若确定data是合法UTF-8,用from_utf8转换为&str打印 println!("{}", std::str::from_utf8(&data)?); // 若存在非UTF-8字节,用from_utf8_lossy自动替换为� // println!("{}", String::from_utf8_lossy(&data)); let mut hasher = Sha256::new(); hasher.input(&data[..]); println!("{}", hasher.result_str().as_str()); self.hash = hasher.result_str();
原理:std::str::from_utf8和String::from_utf8_lossy都接受&[u8]类型参数,仅借用data的内容,不会转移所有权,因此后续data仍可正常使用。
方案2:克隆data再转移所有权
如果必须使用String::from_utf8,可以先克隆data,将克隆后的副本所有权转移给String,原data保留所有权:
let data = self.prepare_hash_data()?; println!("{}", String::from_utf8(data.clone())?); let mut hasher = Sha256::new(); hasher.input(&data[..]); // 后续代码不变
注意:克隆会额外分配内存,仅在特殊场景下使用。
内容的提问来源于stack exchange,提问作者tanmoy
相关产品推荐
相关产品推荐

