4

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?

1
  • 1
    No, because, as you noted, you can't have a field and method with the same name, and you have to implement the Age method to satisfy the interface. Commented Feb 24, 2018 at 3:07

1 Answer 1

9

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})
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.