DEV Community

loading...

Effective Interfaces In Golang

willdoescode profile image Will ・1 min read

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() {

}
Enter fullscreen mode Exit fullscreen mode

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{}) {

}
Enter fullscreen mode Exit fullscreen mode

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")
    }
}
Enter fullscreen mode Exit fullscreen mode

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.

I hope that clears up some confusion about go interfaces

Discussion (1)

pic
Editor guide
Collapse
phantas0s profile image
Matthieu Cneude

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.