Home > Article > Backend Development > 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!