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.

相关推荐
用户0996918801810 小时前
Rust JSON 数据处理:take 与 clone 的权衡
rust
bruce5411012 小时前
Rust学习之实现命令行小工具minigrep(二)
rust
广龙宇15 小时前
【一起学Rust】使用Thunk工具链实现Rust应用对Windows XP/7的兼容性适配实战
开发语言·windows·rust
UestcXiye15 小时前
Rust 学习笔记:安装 Rust
rust
CHQIUU17 小时前
【Rust 精进之路之第2篇-初体验】安装、配置与 Hello Cargo:踏出 Rust 开发第一步
rust
苏近之17 小时前
Rust 重构 Rust:枚举和模式匹配
rust·代码规范
liyu1117 小时前
Tauri 2.x 版本 辅助性 Accessory App 如何实现单例模式 (MAC & Windows)
rust
景天科技苑18 小时前
【Rust所有权机制】Rust所有权机制详细解析与应用实战
开发语言·后端·rust·rust所有权·引用与借用·rust内存安全
柑木19 小时前
Rust-开发必备-cargo_sort-一键整理你的cargo.toml
rust
muyouking111 天前
5.Rust+Axum:打造高效错误处理与响应转换机制
开发语言·后端·rust