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.

相关推荐
alwaysrun4 小时前
Rust中所有权和作用域及生命周期
rust·生命周期·作用域·所有权·引用与借用
FleetingLore19 小时前
Rust | str 常用方法
rust
一只小松许️2 天前
深入理解 Rust 的内存模型:变量、值与指针
java·开发语言·rust
m0_480502643 天前
Rust 登堂 之 Cell 和 RefCell(十二)
开发语言·后端·rust
烈风3 天前
011 Rust数组
开发语言·后端·rust
Dontla4 天前
Turbopack介绍(由Vercel开发的基于Rust的高性能前端构建工具,用于挑战传统构建工具Webpack、vite地位)Next.js推荐构建工具
前端·rust·turbopack
开心不就得了5 天前
构建工具webpack
前端·webpack·rust
ftpeak5 天前
《WebAssembly指南》第九章:WebAssembly 导入全局字符串常量
开发语言·rust·wasm
红烧code6 天前
【Rust GUI开发入门】编写一个本地音乐播放器(15. 记录运行日志)
rust·gui·log·slint
JordanHaidee6 天前
【Rust GUI开发入门】编写一个本地音乐播放器(15. 记录运行日志)
rust