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.

相关推荐
uccs14 小时前
使用 rust 创建多线程 http-server
后端·rust
pumpkin845142 天前
Rust 的核心工具链
rust
SomeB1oody2 天前
【Rust自学】13.8. 迭代器 Pt.4:创建自定义迭代器
开发语言·后端·rust
半夏知半秋2 天前
rust学习-函数的定义与使用
服务器·开发语言·后端·学习·rust
SomeB1oody3 天前
【Rust自学】13.6. 迭代器 Pt.2:消耗和产生迭代器的方法
开发语言·后端·rust
Hello.Reader3 天前
Rust 数据类型详解
开发语言·后端·rust
gs801403 天前
2025年编程语言热度分析:Python领跑,Go与Rust崛起
python·golang·rust
老猿讲编程3 天前
详解Rust 中 String 和 str 的用途与区别
开发语言·后端·rust
rongjv4 天前
[rustGUI][iced]基于rust的GUI库iced(0.13)的部件学习(05):svg图片转为png格式(暨svg部件的使用)
rust·gui·iced
SomeB1oody4 天前
【Rust自学】13.5. 迭代器 Pt.1:迭代器的定义、iterator trait和next方法
开发语言·后端·rust