DEV Community

Will
Will

Posted on

2

Effective Interfaces In Golang

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (1)

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay