Already a member? Log in

Sign up with your...

or

Sign Up with your email address

Add Tags

Duplicate Tags

Rename Tags

Share This URL With Others!

Save Link

Sign in

Sign Up with your email address

Sign up

By clicking the button, you agree to the Terms & Conditions.

Forgot Password?

Please enter your username below and press the send button.
A password reset link will be sent to you.

If you are unable to access the email address originally associated with your Delicious account, we recommend creating a new account.

URL: http://blog.natefinch.com/2014/05/intro-to-go-interfaces.html?spref=tw

Nate Finch's Blog: Intro to Go Interfaces

Go's interfaces are one of it's best features, but they're also one of the most confusing for newbies.  This post will try to give you the understanding you need to use Go's interfaces and not get frustrated when things don't work the way you expect.  It's a little long, but a bunch of that is just code examples.

Go's interfaces are different than interfaces in other languages, they are implicitly fulfilled.  This means that you never need to mark your type as explicitly implementing the interface (like class CFoo implements IFoo).  Instead, your type just needs to have the methods defined in the interface, and the compiler does the rest.

For example:

type Walker interface {

    Walk(miles int)

}

type Camel struct {

    Name string

}

func (c Camel) Walk(miles int) {

     fmt.Printf("%s is walking %v miles\n", c.Name, miles)

}

func LongWalk(w Walker) {

     w.Walk(500)

     w.Walk(500)

}

func main() {

    c := Camel{"Bill"}

    LongWalk(c)

}

// prints

// Bill is walking 500 miles.

// Bill is walking 500 miles.

http://play.golang.org/p/erodX-JplO

Camel implements the Walker interface, because it has a method named Walk that takes an int and doesn't return anything.  This means you can pass it into the LongWalk function, even though you never specified that your Camel is a Walker.  In fact, Camel and Walker can live in totally different packages and never know about one another, and this will still work if a third package decides to make a Camel and pass it into LongWalk.

Non-Standard Continuation

This is where most tutorials stop, and where most questions and problems begin.

Share It With Others!

Comments

joaosodre

Film Director and Writer

Go's interfaces are one of it's best features, but they're also one of the most confusing for newbies. This post will try to give you the understanding you need to use Go's interfaces and not get frustrated when things don't work the way you expect. via Pocket