Dave Pascua
Dave Pascua

Reputation: 321

Go struct field has same name as interface method

From a 3rd party:

package lib

type Bar interface{
  Age() int
}

Foo(b Bar) int

This doesn't compile because Age is both a method name and field name:

package main

import "lib"

type Person struct {
  Age int
}

func (p *Person)Age() int {
  return p.Age
}

func main() {
  p := Person()
  lib.Foo(p)
}

Without renaming Person.Age, is there a way to call lib.Foo() on an instance of Person?

Upvotes: 4

Views: 8007

Answers (1)

Darshan Rivka Whittle
Darshan Rivka Whittle

Reputation: 34061

Well, not directly, of course, for the reasons already stated. But you could create a wrapper around Person, and pass that in:

type BarPerson struct {
    *Person
}

func (bp *BarPerson) Age() int {
    return bp.Person.Age
}

func main() {
    p := Person{37}
    lib.Foo(&BarPerson{&p})
}

Upvotes: 9

Related Questions