繁体   English   中英

如何为 function 参数中的绑定提供默认值?

[英]How to provide a default value for binding in a function argument?

在不包含要绑定的字段的情况下,如何为绑定提供默认文字值?

#[derive(Debug)]
struct Descriptor {
    name: String,
    note: Option<String>,
}

fn func2(
    (d @ Descriptor {
        note: (Some(note_content) | None),
        ..
    }): &Descriptor,
) {
}

这不会编译,因为在None情况下没有对note_content的绑定。 我想指定一个,但我不知道正确的语法。

这并不能解决问题:

Some(note_content) | None, note_content @ "default literal".to_string()

那里应该写什么?

函数中的模式需要是无可辩驳的。 没有办法在 function 的参数中进行模式匹配——它没有意义。

人们使用此功能来解构无可辩驳的模式,如元组。 例如: fn foo((a, b): (&Descriptor, &Descriptor)) ,还有其他用例,但它们是有限的。

您也可以这样做,删除一层命名:

fn func2(Descriptor { name, note }: &Descriptor) {
    let note = note.as_deref().unwrap_or("default literal");
    println!("{}, {}", name, note);
}

您无法匹配像Option这样的可反驳模式,也无法像您要求的那样提供默认值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM