gpt4 book ai didi

rust - 如果没有错误发生,如何返回链接多个结果的成功值,或者如果发生任何错误,如何返回另一个值?

转载 作者:行者123 更新时间:2023-11-29 08:02:28 25 4
gpt4 key购买 nike

我正在尝试链接多个 Result。我想编写一个接收 &[u8] 并返回 Tm 的函数。如果任何步骤出错,我只想返回 time::now()

我写道:

extern crate time;

use time::{strptime, Tm};
use std::str;

pub fn buf_to_tm(buffer: &[u8]) -> Tm {
str::from_utf8(buffer)
.and_then(|val| strptime(val, "%d %b %y%H:%M:%S"))
.unwrap_or(time::now())
}

但是我收到了这个错误:

error[E0308]: mismatched types
--> src/main.rs:8:25
|
8 | .and_then(|val| strptime(val, "%d %b %y%H:%M:%S"))
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `std::str::Utf8Error`, found enum `time::ParseError`
|
= note: expected type `std::result::Result<_, std::str::Utf8Error>`
found type `std::result::Result<time::Tm, time::ParseError>`
= help: here are some functions which might fulfill your needs:
- .unwrap()
- .unwrap_err()

我如何告诉 Rust 我真的不在乎这段代码会给出什么类型的错误,我只想返回解析后的 Tm 如果没有错误发生或 time::now( ) 如果发生任何错误。

最佳答案

由于您不关心哪个错误是失败的原因,您可以通过将两种错误类型映射到 () 以简单的方式解决此问题。 , 或 Result<T, _> => Option<T> , 自 Result<T, ()>同构于Option<T> .

这是通过函数 .ok() 完成的见过here :

extern crate time;

use time::{strptime, Tm};
use std::str;

pub fn buf_to_tm(buffer: &[u8]) -> Tm {
str::from_utf8(buffer).ok()
.and_then(|val| strptime(val, "%d %b %y%H:%M:%S").ok())
.unwrap_or_else(time::now)
}

关于rust - 如果没有错误发生,如何返回链接多个结果的成功值,或者如果发生任何错误,如何返回另一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44438841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com