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.

相关推荐
传奇开心果编程8 小时前
【Rust入门练中学】第6课:结构体与方法
开发语言·rust·结构体·编程语言理论·结构体方法·编程通用语言
本地化文档9 小时前
cutile-rs-book-l10n
rust·gpu·nvidia·cuda·sphinx·crowdin
qq_4069810312 小时前
大白话rust系列09 函数调用两次有什么错?
开发语言·python·rust
康小旺13 小时前
TypeScript 编译器开始卷 Rust 了:Cloudflare 的 tsrs 到底想干嘛?
rust·typescript
Norna13 小时前
时间轮的 +1,为什么最后只留在顶层
rust
轻舟技术A19 小时前
Rust 重写 Pi:会话启动耗时降 91%,就绪内存少 78%
开发语言·后端·rust
unconditional20 小时前
外部命令改不了你的 shell:sdkm 怎么做到"回车即生效"
rust·开源
程工造Agent20 小时前
从 0 到 1 学 Codex 源码:为什么 let b = a 之后,a 就不能用了?
rust·ai编程
Norna20 小时前
方差怎么会是 −32:nushell math variance 的一次数值修复
rust
JavaPub-rodert20 小时前
王仕宇分享:Oxigraph 是什么?用 Rust + RocksDB 搭一个轻量 RDF/SPARQL 知识图谱数据库
数据库·rust·知识图谱