Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rust 为什么要在枚举上匹配单个变量以返回静态';str?_Rust - Fatal编程技术网

Rust 为什么要在枚举上匹配单个变量以返回静态';str?

Rust 为什么要在枚举上匹配单个变量以返回静态';str?,rust,Rust,此代码来自rustc libsyntax/parse/token.rs: pub enum SpecialMacroVar { CrateMacroVar, } impl SpecialMacroVar { pub fn as_str(self) -> &'static str { match self { SpecialMacroVar::CrateMacroVar => "crate", }

此代码来自rustc libsyntax/parse/token.rs:

pub enum SpecialMacroVar {
    CrateMacroVar,
}

impl SpecialMacroVar {
    pub fn as_str(self) -> &'static str {
        match self {
            SpecialMacroVar::CrateMacroVar => "crate",
        }
    }
}
你为什么要这么做,而不是简单地这样做

impl SpecialMacroVar {
    pub fn as_str(self) -> &'static str {
        "crate"
    }
}

也许是出于防御性编程的原因?如果以第二种方式执行,则函数将错误地为每个枚举成员返回
“板条箱”
,即使以后向枚举添加了更多成员,但您忘记将
更新为_str()
,以反映这一事实。然而,通过这种方式,编译器有机会捕捉到此类错误。

可能是出于防御性编程原因?如果采用第二种方法,它将错误地为每个枚举成员返回
“板条箱”
,即使以后向枚举添加了更多成员,但您忘记将
更新为_str()
,以反映这一事实。然而,通过这种方式,编译器有机会捕获此类错误。