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.

相关推荐
明月看潮生3 小时前
青少年编程与数学 02-019 Rust 编程基础 12课题、所有权系统
开发语言·青少年编程·rust·编程与数学
景天科技苑5 小时前
【Rust trait特质】如何在Rust中使用trait特质,全面解析与应用实战
开发语言·后端·rust·trait·rust trait·rust特质
heroboyluck15 小时前
rust 全栈应用框架dioxus server
rust·全栈·dioxus
蜗牛沐雨18 小时前
Rust 中的 `PartialEq` 和 `Eq`:深入解析与应用
开发语言·后端·rust
Python私教18 小时前
Rust快速入门:从零到实战指南
开发语言·后端·rust
明月看潮生20 小时前
青少年编程与数学 02-019 Rust 编程基础 10课题、函数、闭包和迭代器
开发语言·青少年编程·rust·编程与数学
明月看潮生20 小时前
青少年编程与数学 02-019 Rust 编程基础 09课题、流程控制
开发语言·算法·青少年编程·rust·编程与数学
一丝晨光1 天前
数值溢出保护?数值溢出应该是多少?Swift如何让整数计算溢出不抛出异常?类型最大值和最小值?
java·javascript·c++·rust·go·c·swift
景天科技苑1 天前
【Rust泛型】Rust泛型使用详解与应用场景
开发语言·后端·rust·泛型·rust泛型
zhuziheniaoer1 天前
rust-candle学习笔记11-实现一个简单的自注意力
笔记·学习·自然语言处理·rust