Type declarations and the underlying type's methods

70 views
Skip to first unread message

Viktor Kojouharov

unread,
Jan 20, 2017, 2:59:08 AM1/20/17
to golang-nuts
Hello,

Considering how easy it is to create new types based on underlying types, how come the newly created ones do not delegate method calls to their underlying types? Consider the following example:


In the example, calling `b.num()`  directly will not working, one will have to manually do something like `Foo(b).num()` in order to invoke the desired method. Why aren't these methods delegated automatically, similarly to how they are delegated when dealing with embedded structs?

Volker Dobler

unread,
Jan 20, 2017, 3:11:29 AM1/20/17
to golang-nuts
Am Freitag, 20. Januar 2017 08:59:08 UTC+1 schrieb Viktor Kojouharov:
Considering how easy it is to create new types based on underlying types, how come the newly created ones do not delegate method calls to their underlying types? 

The whole idea of a new type is that it has its own method set:
Its behavior is different, otherwise you could use the underlying
type directly. Promoting methods of the underlying type whould
invalidate this whole idea.

V.

jmont...@dyn.com

unread,
Jan 20, 2017, 3:30:05 PM1/20/17
to golang-nuts
should mention that what you want can be achieved with composition using anonymous fields:

https://play.golang.org/p/vEKS70A-29

I know its not your original question, and this only works with `strcut` and `interface`, not build in types, like `int`. But it does give you the kind of behavior you were looking for.
Reply all
Reply to author
Forward
0 new messages