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.

相关推荐
爱编程的小庄19 小时前
Rust初识
开发语言·rust
爱编程的小庄20 小时前
Rust 发行版本及工具介绍
开发语言·后端·rust
skywalk81631 天前
FreeBSD下安装rustup、cargo和uv
开发语言·python·rust·cargo
咸甜适中1 天前
双色球、大乐透兑奖分析小程序(rust_Tauri + Vue3 + sqlite)
爬虫·rust·sqlite·vue3·tauri2
rustfs1 天前
使用 podman 容器化安装 RustFS 详细指南
docker·rust·podman
FAFU_kyp2 天前
Rust 泛型(Generics)学习教程
开发语言·学习·rust
木木木一3 天前
Rust学习记录--C12 实例:写一个命令行程序
学习·算法·rust
柠檬丶抒情3 天前
Rust深度学习框架Burn 0.20是否能超过python?
python·深度学习·rust·vllm
Vallelonga3 天前
浅谈 Rust bindgen 工具
开发语言·rust
木木木一3 天前
Rust学习记录--C13 Part1 闭包和迭代器
开发语言·学习·rust