英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论