1. Reflection
Most languages have the concept of reflection, such as Java, PHP, etc. Golang is no exception. Reflection is actually a mechanism that can self-describe and self-control by programs.
For example, through PHP reflection, you can know what members a class has and what methods it has. golang can also understand various variable types and information through the official reflect package.
Let’s use an example to see the basic usage of reflection.
Without further ado, just post the code:
package main import ( "fmt" "reflect" ) type Order struct { ordId int `json:"order_id" validate:"required"` customerId string `json:"customer_id" validate:"required"` callback func() `json:"call_back" validate:"required"` } func reflectInfo(q interface{}) { t := (q) v := (q) ("Type ", t) ("Value ", v) for i := 0; i < (); i = i + 1 { fv := (i) ft := (i) tag := (i).("json") validate := (i).("validate") switch () { case : ("The %d th %s types: %s, valuing: %s, struct tag: %v\n", i, , "string", (), tag + " " + validate) case : ("The %d th %s types %s, valuing %d, struct tag: %v\n", i, , "int", (), tag + " " + validate) case : ("The %d th %s types %s, valuing %v, struct tag: %v\n", i, , "func", (), tag + " " + validate) } } } func main() { o := Order{ ordId: 456, customerId: "39e9e709-dd4f-0512-9488-a67c508b170f", } reflectInfo(o) }
First, we use (q) and (q) to get the type and value of the structure order, and then we traverse its members from the loop and print out the names and types of all members. In this way, all the information of a structure is exposed to us.
2. Assertion
There is a syntax in Go language that can directly determine whether it is a variable of this type: value, ok = element.(T), where value is the value of the variable, ok is a bool type, element is an interface variable, and T is the type of assertion.
If the element does store a value of type T, then ok returns true, otherwise false.
package main import ( "fmt" ) type Order struct { ordId int customerId int callback func() } func main() { var i interface{} i = Order{ ordId: 456, customerId: 56, } value, ok := i.(Order) if !ok { ("It's not ok for type Order") return } ("The value is ", value) }
Output:
The value is {456 56 <nil>}
Commonly used switch to assert:
package main import ( "fmt" ) type Order struct { ordId int customerId int callback func() } func main() { var i interface{} i = Order{ ordId: 456, customerId: 56, } switch value := i.(type) { case int: ("It is an int and its value is %d\n", value) case string: ("It is a string and its value is %s\n", value) case Order: ("It is a Order and its value is %v\n", value) default: ("It is of a different type") } }
Output:
It is a Order and its value is {456 56 <nil>}
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.