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.

相关推荐
p***43481 小时前
Rust网络编程模型
开发语言·网络·rust
2***65633 小时前
数据库操作与数据管理——Rust 与 SQLite 的集成
数据库·rust·sqlite
q***31836 小时前
Windows安装Rust环境(详细教程)
开发语言·windows·rust
惜棠8 小时前
visual code + rust入门指南
开发语言·后端·rust
n***i958 小时前
Rust在嵌入式系统中的内存管理
开发语言·后端·rust
7***53349 小时前
Rust错误处理模式
开发语言·后端·rust
4***149010 小时前
Rust系统工具开发实践指南
开发语言·后端·rust
5***790015 小时前
Rust在区块链智能合约中的安全实践
rust·区块链·智能合约
q***d17317 小时前
Rust在网络中的协议栈
开发语言·网络·rust
星释17 小时前
Rust 练习册 88:OCR Numbers与光学字符识别
开发语言·后端·rust