Use type-switch to determine the actual storage type of the interface
In go language, interface is very useful, but we often cannot determine what type is stored in the interface, and go is a strongly typed language.
type-switch just helped me solve this problem
//examplevar s interface{} switch s.(type) { case string: ("This is a variable of type string") case int64: ("This is a variable of your type int64") default: ("None of the above types") } //In addition, if you just want to know the type of variable, you can use ()val := "abcdefg123" ((val)) //Print result: string((val)) //DebugPrint results:string
golangan any type of interface{}
In golang, interface{} can be used to represent any type.
This article demonstrates the use of interface{} in the form of an example.
example1
package main import ( "fmt" ) func main() { var t1 interface{} = 2 v, ok := t1.(int) if ok { ("int:", v) } else { ("v:", v) } }
output:
$ ./test
int: 2
Determine the type of interface. If it is an int type, output the value represented by the interface.
Sometimes, if you are sure to know type T (for example, int), you will directly use the following method to assert:
v := t1.(int)
But the assertion fails and will panic. You can choose which method to use according to the specific situation.
example2
package main import ( "fmt" ) func main() { var t1 interface{} = "abc" switch v := t1.(type) { case int: ("int:", v) case string: ("string:", v) default: ("unknown type:", v) } }
If t1 is abc:
output:
$ ./test
string: abc
If t1 is 23:
output:
$ ./test
int: 23
If t1 is 1.2
output:
$ ./test
unknown type: 1.2
The above is personal experience. I hope you can give you a reference and I hope you can support me more.