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.

相关推荐
Rust研习社13 小时前
从碎片化到标准化:cargo-bp 如何重构 Rust 开发逻辑
后端·rust·编程语言
ZTStory14 小时前
mise 一款可以在项目中独立管理语言、环境变量和任务的工具
前端·rust·命令行
咸甜适中14 小时前
rust语言学习笔记Trait(十一)Deref、DerefMut(解引用)
笔记·学习·rust
特立独行的猫a19 小时前
AtomMQTT--使用Rust语音实现的轻量级高性能MQtt服务器
服务器·开发语言·mqtt·rust·broker
恋喵大鲤鱼20 小时前
Rust 结构体分类
rust·struct
Rust研习社20 小时前
Tonic 加入 gRPC 官方项目,Rust 云原生生态进入了新阶段
开发语言·后端·云原生·rust
望眼欲穿的程序猿1 天前
Rust+STM32F103
嵌入式硬件·rust
星栈独行1 天前
我在 Rust 全栈项目里用 JWT 做无状态认证
开发语言·后端·rust·前端框架·开源·github·web
Vallelonga1 天前
Rust Conversion 工具 trait AsRef AsMut
开发语言·rust
Vallelonga1 天前
Rust 中的“解引用”和智能指针与 MutexGuard 等
开发语言·rust