rust 使用选项匹配枚举的问题[已关闭]

uelo1irk  于 2023-05-17  发布在  其他
关注(0)|答案(1)|浏览(154)

**关闭。**此题需要debugging details。目前不接受答复。

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将帮助其他人回答这个问题。
6天前关闭。
Improve this question
我有这个解析器用来解析邮件,我需要解析来自我使用rust mail_parser crate的细节。在那里,使用from方法从详细信息中提取已解析的输入from方法返回名为HeaderValuelink的枚举
我不明白的是,如果我需要得到Address(Addr<'x>)的地址是一个选项,其中包含此选项

pub struct Addr<'x> {
    pub name: Option<Cow<'x, str>>,
    pub address: Option<Cow<'x, str>>,
}

什么我得到的问题是不能使匹配得到数据从Address(Addr<'x>)和提取选项。如果我需要得到的nameaddress字段的结构,我如何使match语句?.

8i9zcol2

8i9zcol21#

这并不难,只是标准语法。你到底犯了哪些错误?

use std::borrow::Cow;

pub struct Addr<'x> {
    pub name: Option<Cow<'x, str>>,
    pub address: Option<Cow<'x, str>>,
}

pub enum HeaderValue<'x> {
    Address(Addr<'x>),
    AddressList(Vec<Addr<'x>>),
    Empty,
}

fn main() {
    let value = HeaderValue::Address(Addr{name: Some("somename".into()), address: None});
    match value {
        HeaderValue::Address(Addr{name, address}) => println!("Parsed name={:?} address={:?}", name, address),
        _ => println!("Couldn't match"),
    }
}

打印
解析的名称=Some(“somename”)地址=无
或者对于匹配不同组合的更多控制:

match value {
        HeaderValue::Address(Addr{name:Some(name), address:Some(address)}) => println!("Parsed both name={:?} address={:?}", name, address),
        HeaderValue::Address(Addr{address:Some(address), ..}) => println!("Parsed only address={:?}", address),
        HeaderValue::Address(Addr{name:Some(name), ..}) => println!("Parsed only name={:?}", name),
        HeaderValue::Address(Addr{..}) => println!("Parsed empty"),
        _ => println!("Couldn't match"),
}

打印
仅解析name=“somename”

评论回复:

我不认为您可以用一个match语句做到这一点,但您可以像这样做多个if let语句

let value = HeaderValue::Address(Addr{name: Some("somename".into()), address: None});
if let HeaderValue::Address(Addr{address:Some(address), ..}) = &value {
    println!("Parsed address={:?}", address);
}
if let HeaderValue::Address(Addr{name:Some(name), ..}) = &value {
    println!("Parsed name={:?}", name);
}

图纸:
解析名称=“somename”

相关问题