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.

相关推荐
寻月隐君4 小时前
Rust 网络编程实战:用 Tokio 手写一个迷你 TCP 反向代理 (minginx)
后端·rust·github
芳草萋萋鹦鹉洲哦11 小时前
【vue3+tauri+rust】如何实现下载文件mac+windows
windows·macos·rust
寻月隐君19 小时前
Rust 异步编程实践:从 Tokio 基础到阻塞任务处理模式
后端·rust·github
萧曵 丶1 天前
Rust 中的返回类型
开发语言·后端·rust
浪裡遊1 天前
Sass详解:功能特性、常用方法与最佳实践
开发语言·前端·javascript·css·vue.js·rust·sass
受之以蒙1 天前
Rust & WASM 之 wasm-bindgen 基础:让 Rust 与 JavaScript 无缝对话
前端·笔记·rust
Elixin1 天前
第一章:环境搭建
rust
Pomelo_刘金2 天前
Rust 宣布发布1.88.0
rust
寻月隐君2 天前
告别 Vec!掌握 Rust bytes 库,解锁零拷贝的真正威力
后端·rust·github
大卫小东(Sheldon)2 天前
GIM 1.5发布了! 支持Windows系统了
git·ai·rust