You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust函数报错E0382:已移动值`inb`的使用问题求助

解决Rust中"use of moved value"错误(orgize库write_html调用问题)

你遇到的E0382错误核心原因是:Vec<u8>未实现Copy trait,调用write_html(inb)时,inb的所有权被完全转移给了该方法,后续代码再尝试使用inb时,它已经不属于当前作用域了。

解决方案

不需要转移inb的所有权,只需传递它的可变引用给write_html即可。因为write_html仅需要一个实现std::io::Write的对象,&mut Vec<u8>同样满足这个要求,且不会转移所有权。

修正后的完整代码:

use orgize::Org;

fn convert(i: String) -> String {
    let mut inb = Vec::new(); // 添加mut声明,允许获取可变引用
    Org::parse_string(i).write_html(&mut inb); // 传递可变引用而非所有权
    String::from_utf8(inb).unwrap()
}

优化建议(避免panic)

如果要规避unwrap()可能引发的运行时panic,实际项目中推荐返回Result类型来优雅处理错误:

use orgize::Org;
use std::error::Error;

fn convert(i: String) -> Result<String, Box<dyn Error>> {
    let mut inb = Vec::new();
    Org::parse_string(i).write_html(&mut inb)?;
    let out = String::from_utf8(inb)?;
    Ok(out)
}

内容的提问来源于stack exchange,提问作者Atlas Sullivan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 21:25:24