In go interfaces are useful to use in functions that you want to support multiple types
To start we need to create a function
func hello() {
}
I want this function to be able to take strings, ints, and floats. How would I do this?
With an interface{} parameter
func hello(s interface{}) {
}
Now how to add handling for the types that you may find in an interface with a switch statement.
func hello(s interface{}) {
switch s.(type) {
case int:
fmt.Printf("%d", s.(int))
case float64:
fmt.Printf("%d", s.(float64))
case string:
fmt.Printf("%s", s.(string))
default:
fmt.Printf("No handling for this type")
}
}
This is an easy way to add handling for interface types using a switch statement.
Know that s.(type)
can only be used within a switch statement.
You may notice the use of s.(int)
and s.(string)
This is simply telling the compiler that you would like to use the interface as a string or the interface as an int so that you can use functions that are associated with said type.
Top comments (1)
This is currently the only way to manage generic programming in Golang (with reflection but, I mean, be very careful with that). But generics are coming, and when it will be officially rolled out we shouldn't use this kind of code anymore.