Cách biểu diễn enums theo idiomatic trong Go là gì?
Cách biểu diễn enums theo idiomatic trong Go là gì?
Go không có enum từ khoá; cách idiomatic là kiểu mới + hằng số với iota.
type Status int
const (
Pending Status = iota // 0
Active // 1
Closed // 2
)
func (s Status) String() string {
switch s {
case Pending: return "pending"
case Active: return "active"
case Closed: return "closed"
default: return fmt.Sprintf("Status(%d)", int(s))
}
}
// Với chuỗi
type Role string
const (
RoleAdmin Role = "admin"
RoleUser Role = "user"
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.