Return Consumed Argument on Error

Return Consumed Argument on Error

From: https://rust-unofficial.github.io/patterns/idioms/return-consumed-arg-on-error.html

For better performance, the argument is usually moved into function.

Take the example of String::from_utf8():

rust 复制代码
pub fn from_utf8(vec: Vec<u8>) -> Result<String, SomeError>

But if I need to convert my vec to string after String::from_utf8() failed:

rust 复制代码
    let res = String::from_utf8(my_vec);
    match res {
        Ok(s) => println!("utf8 string is {s:?}"),
        Err(_) => convert_non_utf8_to_string(my_vec),
    }

There is compile error because my_vec is moved in String::from_utf8():

4 |     let res = String::from_utf8(my_vec);
  |                                 ------ value moved here
...
7 |         Err(e) => convert_non_utf8_to_string(my_vec),
  |                                              ^^^^^^ value used here after move
  |
help: consider cloning the value if the performance cost is acceptable
  |
4 |     let res = String::from_utf8(my_vec.clone());
  |                                       ++++++++

Cloning the my_vec can do but it takes a performance cost.

Luckly String::from_utf8() returns the original vec on error:

rust 复制代码
pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error>
rust 复制代码
// some invalid bytes, in a vector
let bytes = vec![0, 159];

let value = String::from_utf8(bytes);

assert!(value.is_err());
assert_eq!(vec![0, 159], value.unwrap_err().into_bytes());

The trick is: if a fallible function consumes an argument, returns the argument back inside the error.

相关推荐
Hello.Reader15 分钟前
深入理解 Rust 的 `Rc<T>`:实现多所有权的智能指针
开发语言·后端·rust
yoona102018 分钟前
Rust编程语言入门教程(八)所有权 Stack vs Heap
开发语言·后端·rust·区块链·学习方法
guyoung2 小时前
DeepSeek轻量级本地化部署工具——AIMatrices DeepSeek
rust·llm·deepseek
JD技术委员会7 小时前
Rust 语法噪音这么多,是否适合复杂项目?
开发语言·人工智能·rust
Hello.Reader7 小时前
Rust 中的 `Drop` 特性:自动化资源清理的魔法
开发语言·rust·自动化
Vitalia7 小时前
从零开始学 Rust:基本概念——变量、数据类型、函数、控制流
开发语言·后端·rust
cheungxiongwei.com7 小时前
Rust 驱动的 Python 工具革命:Ruff 和 uv 与传统工具的对比分
python·rust·uv
wzhao1017 小时前
elf_loader:一个使用Rust编写的ELF加载器
linux·rust·gnu
泡泡Java9 小时前
使用WebStorm开发Vue3项目
ide·rust·webstorm
独好紫罗兰2 天前
通过例子学 rust 个人精简版 5-all
rust