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.

相关推荐
浪客川10 小时前
【百例RUST - 014】Trait
服务器·网络·rust
shimly12345610 小时前
RUST impl <T> Wrapper <T>
rust
Rust语言中文社区10 小时前
【Rust日报】Clone:像进程一样 fork 虚拟机的 Rust KVM VMM
开发语言·后端·rust
编码浪子11 小时前
基于 Rust + Axum 的企业级权限管理系统设计与实现
开发语言·后端·rust
techdashen12 小时前
Rust 1.88 终于稳定了裸函数:写汇编不再需要那堆样板代码
汇编·rust
shimly12345612 小时前
RUST Display Debug {} {:?}
rust
代码羊羊14 小时前
Rust方法速览:从self到impl
开发语言·后端·rust
shimly12345615 小时前
PhantomData 的例子、用途
rust
Rust研习社15 小时前
Rust 静态生命周期:从概念到实战避坑
后端·rust·编程语言
古城小栈16 小时前
2026 年 Rust 异步 HTTP 首选:reqres,轻量、高效、开箱即用
网络·http·rust