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.

相关推荐
我是前端小学生2 天前
一文梳理Rust语言中的可变结构体实例
rust
Source.Liu2 天前
【unitrix数间混合计算】2.21 二进制整数加法计算(bin_add.rs)
rust
Include everything2 天前
Rust学习笔记(二)|变量、函数与控制流
笔记·学习·rust
Source.Liu2 天前
【unitrix数间混合计算】2.20 比较计算(cmp.rs)
rust
许野平2 天前
Rust:构造函数 new() 如何进行错误处理?
开发语言·后端·rust
许野平2 天前
Rust:专业级错误处理工具 thiserror 详解
rust·error·错误处理·result·thiserror
蒋星熠2 天前
Rust 异步生态实战:Tokio 调度、Pin/Unpin 与零拷贝 I/O
人工智能·后端·python·深度学习·rust
Include everything2 天前
Rust学习笔记(一)|Rust初体验 猜数游戏
笔记·学习·rust
华科云商xiao徐3 天前
Rust+Python双核爬虫:高并发采集与智能解析实战
数据库·python·rust