A brief analysis of how to implement enumeration in Golang (with code)
How to implement enumeration in Golang? The following article will introduce to you the method of implementing enumeration in Golang. I hope it will be helpful to you!

In the field of programming, enumerations are used to represent types that contain only a limited number of fixed values. They are generally used to identify error codes or state machines in development. Take the state machine of an entity object as an example. It usually corresponds to the field value that identifies the state of the corresponding record of this object in the database. [Related recommendations: Go Video Tutorial]
When you first started learning programming, you must have written, or at least seen, code that directly uses magic numbers to make judgments. What is a magic number? For example, when you want to pin an article to the top, you must first determine whether the article has been published.
if (article.state == 2) {
// state 2 代表文章已发布
}If there are no comments in our code, or when the code of our project is filled with these magic number judgments, will you have a headache?
Later I learned to define these status values as constants, and also developed a method to determine the status of the object to encapsulate this logic separately.
public class ArticleState {
public static final int Draft = 1; //草稿
public static final int Published = 2; //发布
public static final int Deleted = 3; // 已删除
}
public Boolean checkArticleState(int state) {
...
}This usage is definitely much better than directly using magic numbers to make judgments in the program. At least it won’t give you a headache or want to curse.
However, the big brother who took me there later said that this method also has shortcomings. The above checkArticleState method is used to check the article status. It is intended to let the caller pass in one of the three static constants of ArticleState, but because there is no Type constraints, so passing in any int value is syntactically allowed, and the compiler will not issue any warnings. It is more appropriate to use an enumeration.
em~! I don’t remember the teacher talking about this thing during the semester when I taught Java in college. Could it be another knowledge point that I missed while playing on my mobile phone in class? So after using the enumeration, our Java code becomes:
// 使用enum而非class声明
public enum ArticleState {
//要在enum里创建所有的枚举对象
Draft(1, "草稿");
Published(2, "已发布");
Deleted(3, "已删除")
// 自定义属性
private int code;
private String text;
// 构造方法必须是private的
ArticleState(int code, String text) {
this.code = id;
this.text = name;
}
}
public Boolean checkArticleState(ArticleState state) {
...
}This way we can use the enumeration type of the formal parameter to help us filter out illegal state values, and pass the integer value as a parameter to the checkArticleState method. Because the type mismatch cannot be compiled, the compiler can prompt it immediately when writing code.
If you haven’t used Java before, don’t worry. I’ve marked the main grammatical points with comments, and everyone should be able to understand it.
In the past two years, I mainly used Go to do projects. I found that similar problems existed in Go, but Go did not provide enumeration types. So how to correctly limit the status value? It definitely won’t work if you still use int-type constants. For example:
const (
Draft int = 1
Published = 2
Deleted = 3
)
const (
Summer int = 1
Autumn = 2
Winter = 3
Spring = 4
)
func main() {
// 输出 true, 不会有任何编译错误
fmt.Println(Autumn == Draft)
}For example, two sets of int type constants are defined above, one represents the status of the article, and the other represents the four seasons. There will be no compilation errors when comparing article status with seasons this way.
The answer can be found in the code of Go's built-in library or some open source libraries that we all know. For example, if you look at how gRPC error codes are defined in google.golang.org/grpc/codes, you can understand how to implement enumeration correctly.
We can use int as the basic type to create an alias type. Go supports this.
type Season int const ( Summer Season = 1 Autumn = 2 Winter = 3 Spring = 4 )
Of course, when defining continuous constant values, iota is often used in Go, so the above definition is still valid. can be further simplified.
type Season int
const (
Summer Season = iota + 1
Autumn
Winter
Spring
)
type ArticleState int
const (
Draft int = iota + 1
Published
Deleted
)
func checkArticleState(state ArticleState) bool {
// ...
}
func main() {
// 两个操作数类型不匹配,编译错误
fmt.Println(Autumn == Draft)
// 参数类型不匹配,但是因为 ArticleState 底层的类型是 int 所以传递 int 的时候会发生隐式类型转换,所以不会报错
checkArticleState(100)
}Although the underlying types of these status values are all int values, comparing enumeration values of two unrelated types will cause compilation errors, because now we use status values everywhere. Type restrictions.
However, the parameter type of the function checkArticleState is set to ArticleState because the underlying type of ArticleState is int. Therefore, when calling checkArticleState, passing int type parameters will cause implicit type conversion and will not cause compilation errors. If you want to solve this problem, you can only redefine the type to achieve it.
You can refer to StackOverflow This answer:
https://stackoverflow.com/questions/50826100/how-to-disable-implicit-type-conversion-for-constants
More programming related For knowledge, please visit: programming video! !
The above is the detailed content of A brief analysis of how to implement enumeration in Golang (with code). For more information, please follow other related articles on the PHP Chinese website!
The Performance Race: Golang vs. CApr 16, 2025 am 12:07 AMGolang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.
Golang vs. C : Code Examples and Performance AnalysisApr 15, 2025 am 12:03 AMGolang is suitable for rapid development and concurrent programming, while C is more suitable for projects that require extreme performance and underlying control. 1) Golang's concurrency model simplifies concurrency programming through goroutine and channel. 2) C's template programming provides generic code and performance optimization. 3) Golang's garbage collection is convenient but may affect performance. C's memory management is complex but the control is fine.
Golang's Impact: Speed, Efficiency, and SimplicityApr 14, 2025 am 12:11 AMGoimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:
C and Golang: When Performance is CrucialApr 13, 2025 am 12:11 AMC is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.
Golang in Action: Real-World Examples and ApplicationsApr 12, 2025 am 12:11 AMGolang excels in practical applications and is known for its simplicity, efficiency and concurrency. 1) Concurrent programming is implemented through Goroutines and Channels, 2) Flexible code is written using interfaces and polymorphisms, 3) Simplify network programming with net/http packages, 4) Build efficient concurrent crawlers, 5) Debugging and optimizing through tools and best practices.
Golang: The Go Programming Language ExplainedApr 10, 2025 am 11:18 AMThe core features of Go include garbage collection, static linking and concurrency support. 1. The concurrency model of Go language realizes efficient concurrent programming through goroutine and channel. 2. Interfaces and polymorphisms are implemented through interface methods, so that different types can be processed in a unified manner. 3. The basic usage demonstrates the efficiency of function definition and call. 4. In advanced usage, slices provide powerful functions of dynamic resizing. 5. Common errors such as race conditions can be detected and resolved through getest-race. 6. Performance optimization Reuse objects through sync.Pool to reduce garbage collection pressure.
Golang's Purpose: Building Efficient and Scalable SystemsApr 09, 2025 pm 05:17 PMGo language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.
Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Apr 02, 2025 pm 05:24 PMConfused about the sorting of SQL query results. In the process of learning SQL, you often encounter some confusing problems. Recently, the author is reading "MICK-SQL Basics"...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 English version
Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment






