如何在Rust中添加另一个枚举变体而不会影响库用户?

huangapple go评论67阅读模式
英文:

How can I add another enum variant in Rust without breaking library users?

问题

在我的Rust库中的某处定义了以下枚举类型:

#[derive(Debug)]
pub enum Color {
    Red,
    Green,
    Blue,
}

当我向该枚举添加第四个变体Color::Yellow时,是否被视为破坏性更改?如果它被视为破坏性更改(我猜是因为match语句),是否有一种方法可以向API用户指示该类型可能在将来扩展?

英文:

Assume the following enumeration type is defined somewhere in my Rust library:

#[derive(Debug)]
pub enum Color {
    Red,
    Green,
    Blue,
}

Is it considered a breaking change when I add a fourth variant Color::Yellow to the enum? If it is a breaking change (I guess so because of the match statement), is there a way to indicate to API users that this type might be extended in the future?

答案1

得分: 3

是的,添加一个枚举变体被视为一个破坏性的变更。在Rust RFC 1105 - API演进中可以阅读更多相关信息 这里

你可以在你的枚举上添加#[non_exhaustive]属性,以警告你的用户,你可能在未来扩展你的枚举以包含更多的变体,这样添加一个新的变体就不会被视为破坏性变更:

#[non_exhaustive]
#[derive(Debug)]
pub enum Color {
    Red,
    Green,
    Blue,
}

这会禁止导入你的枚举的项目进行非穷尽匹配。例如:

match color {
    Color::Red => (),
    Color::Green => (),
    Color::Blue => (),
}

会抛出错误,而

match color {
    Color::Red => (),
    Color::Green => (),
    Color::Blue => (),
    _ => (),
}

则不会。

英文:

Yes, adding an enum variant is considered a breaking change. Read more about it in the Rust RFC 1105 - API evolution here.

You can add the #[non_exhaustive] attribute to your enum to warn your users that you may extend your enum with further variants in the future, so adding a new variant won't be considered a breaking change:

#[non_exhaustive]
#[derive(Debug)]
pub enum Color {
    Red,
    Green,
    Blue,
}

This disallows projects that import your enum to non-exhaustively match it. I.e.:

match color {
    Color::Red => (),
    Color::Green => (),
    Color::Blue => (),
}

throws an error, while

match color {
    Color::Red => (),
    Color::Green => (),
    Color::Blue => (),
    _ => (),
}

won't.

huangapple
  • 本文由 发表于 2023年3月9日 17:55:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75682935.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定