thp-lang.org/md/learn/data-structures/enums.md

52 lines
492 B
Markdown
Raw Normal View History

2024-03-16 14:30:32 +00:00
# Enums (Tagged unions)
2023-10-02 01:41:38 +00:00
## Basic enums
```thp
enum Suit
{
Hearts,
Diamonds,
Clubs,
Spades,
}
2024-02-20 10:53:38 +00:00
val suit = Suit::Hearts
2023-10-02 01:41:38 +00:00
```
## Enums with values
```thp
enum IpAddress
{
V4(String),
V6(String),
}
2024-02-20 10:17:21 +00:00
val addr_1 = IpAddress::V4("192.168.0.1")
2023-10-02 01:41:38 +00:00
match addr_1
2024-03-16 14:30:32 +00:00
case IpAddress::V4(ip)
2023-10-02 01:41:38 +00:00
{
// code..
}
2024-03-16 14:30:32 +00:00
case IpAddress::V6(ip)
2023-10-02 01:41:38 +00:00
{
// more code..
}
// Without the full qualifier
match addr_1
2024-03-16 14:30:32 +00:00
case ::V4(ip)
2023-10-02 01:41:38 +00:00
{
// code...
}
2024-03-16 14:30:32 +00:00
case ::V6(ip)
2023-10-02 01:41:38 +00:00
{
// even more code...
}
```