Why is there no enumeration in golang?

(*-*)浩
Release: 2019-12-31 10:59:31
Original
4222 people have browsed it

Why is there no enumeration in golang?

In high-level languages ​​such as c# and java, enumeration types are often used to represent states, etc.

There is no enumeration type in golang. You can use const to simulate the enumeration type.                                                                                                                                                                                             (Recommended learning: go)

Enumeration can create a new type of variable based on any data type among Integer, Long, Short or Byte. Such variables can be set to one of a defined set, effectively preventing users from providing invalid values. This variable makes the code clearer because it describes a specific value.

type PolicyType int32const (
    Policy_MIN      PolicyType = 0
    Policy_MAX      PolicyType = 1
    Policy_MID      PolicyType = 2
    Policy_AVG      PolicyType = 3)
}
Copy after login

A new type PolicyType is defined here, and four constants (Policy_MIN, Policy_MAX, Policy_MID, Policy_AVG) are defined. The type is PolicyType.

Usage examples

func foo(p PolicyType) {
    fmt.Printf("enum value: %v\n", p)}func main() {
    foo(Policy_MAX)}
Copy after login

Run results

$ go build && ./main
enum value: 1
Copy after login

The above is the detailed content of Why is there no enumeration in golang?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template