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.

相关推荐
土豆12508 小时前
Rust 错误处理完全指南:从入门到精通
前端·rust·编程语言
Yuer202510 小时前
用 Rust 做分布式查询引擎之前,我先写了一个最小执行 POC
开发语言·分布式·rust
问道飞鱼11 小时前
【Rust编程语言】Rust数据类型全面解析
开发语言·后端·rust·数据类型
王燕龙(大卫)13 小时前
rust:智能指针
rust
唐装鼠14 小时前
Rust transmute(deepseek)
开发语言·rust
laocooon52385788615 小时前
Rust 编程语言教学目录
开发语言·后端·rust
小希smallxi15 小时前
Rust语言入门
开发语言·后端·rust
进击的前栈16 小时前
Flutter跨平台网络图片缓存库cached_network_image鸿蒙化适配指导手册
开发语言·网络·rust
前端小天才20 小时前
element-ui图标偶现乱码问题的原因和修复方法
开发语言·ui·rust
Yuer202520 小时前
WebRTC 实时语音交互如何支持“可中断”?为什么状态机(FSM)是绕不开的方案
算法·rust·webrtc·fsm