[Rust] Intro Enum
Go Enum
package main
type GoEnum = int
const (
Foo GoEnum = iota
Bar
Baz
)
func main() {
}
Typescript Enum
enum TsEnum {
Foo,
Bar,
Baz
}
Rust Enum
enum RsEnum {
Foo,
Bar,
Baz
}
Why go over enums...
They are simple constructs. But you can add types to Rust Enum.
enum TsEnum {
Foo(i32),
Bar(String),
Baz(Vec<String>)
}
Example:
enum TsEnum {
Foo(i32),
Fuu(Option<i32>),
Bar(String),
Baz(Vec<String>)
}
fn main() {
// set value 5
let foo = RsEnum::Foo(5);
// pattern matching, pick the value
if let RsEunm::Foo(value) = foo {
}
// or you can also do
match foo {
RsEnum::Foo(value) => {},
RsEnum::Fuu(Some(value)) => { /* Has value */ },
RsEnum::Fuu(None) => { /* Doesn't has value */ },
_ => { /* Cover the rest cases */ }
}
}
We can also do generic on them
enum Foo<T> {
Bar(T)
}
How is this paractically useful?
- lists with many types
- Nullable
- Error Handling
Example of nullable in TS
type Foo = {
bar?: string
}
function doSomething(foo: Foo): boolean {
if (foo.bar) {
return true
} else {
// ...
return false
}
}
in Rust
enum Option<T> {
None,
Some(T)
}
fn main () {
let foo = Some(5)
if let Some(value) = foo {
// then value is i32
}
match foo {
Some(value) => { /* value is i32*/ },
None => {}
}
// the same as in TS: foo.amp((x) => {})
// do the transform fn only when there is a value
foo.map(|x| => {
})
foo.filter(|&x| x < 10)
if foo.is_some() {
let sum = foo.unwrap() + 5;
};
foo.unwrap_or(0);
foo.unwrap_or_else(|| {
return 5
})
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2021-02-12 [Bash] Schedule Timed Jobs on macOS with `launchd`
2021-02-12 [Bash] Create a Bash Script that Accepts Named Options with getopts
2021-02-12 [Bash] Use case for Complicated Conditional Statements in Bash
2021-02-12 [Bash] Run `npm install` when package.json changes in githook
2021-02-12 [Bash] Use jq and grep to Find Unused Dependencies in a Project
2020-02-12 [Angular 8 Unit Testing] Angular 8 Unit Testing -- service
2020-02-12 [Algorithm] 448. Find All Numbers Disappeared in an Array