SoFunction
Updated on 2025-03-05

Example of tutorial on using enumeration types in go doudou application

Go language supports syntax to implement enum types by itself

We all know that the Go language does not have native enumeration types, but sometimes when doing business development, there are indeed inconvenient front-end joint debugging without enumeration types. We can implement enum types by ourselves through the syntax supported by the Go language. Please see the following sample code and comment description:

// First define an int type alias, the new type name is the enum type nametype KeyboardLayout int
// Then define several constants as enum values// The first constant is the default valueconst (
	UNKNOWN KeyboardLayout = iota
	QWERTZ
	AZERTY
	QWERTY
)
// Define the setter method and convert the enumeration value of the passed string type into the constant defined abovefunc (k *KeyboardLayout) StringSetter(value string) {
	switch value {
	case "UNKNOWN":
		*k = UNKNOWN
	case "QWERTY":
		*k = QWERTY
	case "QWERTZ":
		*k = QWERTZ
	case "AZERTY":
		*k = AZERTY
	default:
		*k = UNKNOWN
	}
}
// There is naturally a getter if there is a setterfunc (k *KeyboardLayout) StringGetter() string {
	switch *k {
	case UNKNOWN:
		return "UNKNOWN"
	case QWERTY:
		return "QWERTY"
	case QWERTZ:
		return "QWERTZ"
	case AZERTY:
		return "AZERTY"
	default:
		return "UNKNOWN"
	}
}
// Finally, define a set of UnmarshalJSON and MarshalJSON methods// UnmarshalJSON is used for json deserializationfunc (k *KeyboardLayout) UnmarshalJSON(bytes []byte) error {
	var _k string
	err := (bytes, &_k)
	if err != nil {
		return err
	}
	(_k)
	return nil
}
// MarshalJSON is used for json serializationfunc (k KeyboardLayout) MarshalJSON() ([]byte, error) {
	return (())
}

After definition, it can be used directly as the attribute type of the structure or the interface request parameter type.

Structure type example

type Keyboard struct {
	Layout  KeyboardLayout `json:"layout,omitempty"`
	Backlit bool            `json:"backlit,omitempty"`
}

Example of interface request parameters

type EnumDemo interface {
	GetKeyboard(ctx , layout ) (data string, err error)
	GetKeyboard2(ctx , layout *) (data string, err error)
	GetKeyboards(ctx , layout []) (data []string, err error)
	GetKeyboards2(ctx , layout *[]) (data []string, err error)
	GetKeyboards5(ctx , layout ...) (data []string, err error)
	Keyboard(ctx , keyboard ) (data string, err error)
}

Complete sample code:/unionj-clou…

For more features and usage of go-doudou, please refer to the official documentation:/

go-doudouMicroservice framework

The above is the detailed content of the tutorial example of using enumeration types in the go doudou application. For more information about go doudou enumeration types, please follow my other related articles!