Hacker News new | ask | show | jobs
by quarterto 4596 days ago
This is called a type assertion in Go. Whenever you ask for something as an interface but want to use the type's own method, you have to make a type assertion.

  interface Fooer {
    func Foo()
  }

  type Bar struct {}

  func (s Bar) Foo() {}
  func (s Bar) Baz() {}

  func DoFoo(f Fooer) {
    f.Foo() // fine
    // f.Baz() compile error
    f.(Bar).Baz() // fine
  }
1 comments

Isn't the entire point of an interface to communicate the behaviour expected by the function though?

If you want a Bar specifically (as the DoFoo code does above), it should take a Bar as an argument.

If you want to accept any struct that satisfies Fooer, add all the methods to Fooer that you need them to satisfy...

Doing otherwise is just subverting the type system and you might as well use a blank interface and effectively have no type checking on your input - if you require a Fooer and then typecast someone might pass a Fooer and get a nasty surprise when it doesn't work.