How does golang use type-switch to determine the actual storage type of interface variables
This article mainly explains the "golang how to use type-switch to determine the actual storage type of interface variables", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "golang how to use type-switch to determine the actual storage type of interface variables" bar!
Using type-switch to determine the actual storage type of interface
Interface is easy to use in the go language, but we are often not sure what type is stored in interface, and go is a strongly typed language.
Type-switch happens to help me solve this problem / / example var s interface {} switch s. (type) {case string: fmt.println ("this is a variable of type string") case int64: fmt.println ("this is a variable of your int64 type") default: fmt.println ("none of the above types")} / / in addition, if you simply want to know the type of variable You can use reflect.typeof () val: = "abcdefg123" fmt.println (reflect.typeof (val)) / / print results: stringbeego.Debug (reflect.typeof (val)) / / Debug print results: stringgolang any type of interface {}
You can use interface {} to represent any type in golang.
This article demonstrates the use of interface {} in the form of an example.
Example1package mainimport ("fmt") func main () {var T1 interface {} = 2v, ok: = T1. (int) if ok {fmt.Println ("int:", v)} else {fmt.Println ("v:", v)}}
Output:
$. / test
Int: 2
Determine the type of interface, and if it is int, output the value represented by the interface.
Sometimes, if you are sure you know the type T (for example, int), you will assert it directly in the following way:
V: = T1. (int)
But if the assertion fails, it will panic. You can choose which method to use according to the specific situation.
Example2package mainimport ("fmt") func main () {var T1 interface {} = "abc" switch v: = T1. (type) {case int: fmt.Println ("int:", v) case string: fmt.Println ("string:", v) default: fmt.Println ("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
Thank you for your reading, the above is the content of "how golang uses type-switch to judge the actual storage type of interface variables". After the study of this article, I believe you have a deeper understanding of how golang uses type-switch to judge the actual storage type of interface variables, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!