Define methods for non-local types

1,047 views
Skip to first unread message

Joan Miller

unread,
Apr 3, 2010, 1:31:06 PM4/3/10
to golang-nuts
Is possible to define new methods for types that are in another
package? How?

Joan Miller

unread,
Apr 3, 2010, 1:34:13 PM4/3/10
to golang-nuts
It isn't possible

"The base type must not be a pointer or interface type and must be
declared in the same package as the method."

Steven

unread,
Apr 3, 2010, 1:53:50 PM4/3/10
to Joan Miller, golang-nuts
Yes, this is the kind of thing you look in the documentation for before asking :P It would be confusing if by importing a package, you changed the definition of a type you get from a third package. And what if two packages you import try to define a method with the same name on a type? What happens when one package has a different definition for a type than another, and it is put in an interface? It just doesn't make much sense.

However, you can define functions that work with a type, it just won't let you satisfy an interface. An alternative is to use embedding:

type MyExtension struct {
    otherPackage.Type

func (me *MyExtension) NewMethod() { ... }


Ian Lance Taylor

unread,
Apr 3, 2010, 1:56:02 PM4/3/10
to Joan Miller, golang-nuts
Joan Miller <pelo...@gmail.com> writes:

> Is possible to define new methods for types that are in another
> package? How?

As has been discussed on the mailing list in the past, this is not
possible. The problem is that it means that different packages will
see different sets of methods for the type, implying that the type
will satisfy different interfaces in different packages. If you then
start passing values of the type to a third package, which interfaces
the values will satisfy there becomes very obscure.

Ian

Reply all
Reply to author
Forward
0 new messages