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.

相关推荐
ai安歌19 小时前
【Rust编程:从新手到大师】Rust变量深度详解
rust
G_dou_20 小时前
智能指针完全指南
windows·rust
G_dou_1 天前
并发编程基础
算法·rust
ai安歌1 天前
【Rust编程:从新手到大师】 Rust 控制流深度详解
开发语言·算法·rust
G_dou_1 天前
借用与引用实战
rust
The 旺1 天前
【Rust实战】打造内存安全的网络代理:深入异步IO与并发编程
网络·安全·rust
RustCoder1 天前
RustNet:使用 Rust 开发的跨平台网络监控工具
安全·rust·开源
Xxtaoaooo1 天前
Rust Actix-web框架源码解析:基于Actor模型的高性能Web开发
rust·源码分析·高性能·并发安全·actix-web
鼓掌MVP1 天前
Rust Web实战:构建高性能并发工具的艺术
开发语言·前端·rust·异步编程·内存安全·actix-web·高性能web服务
盒马盒马1 天前
Rust:函数与控制流
开发语言·网络·rust