Embedding an interface with a function type

68 views
Skip to first unread message

Victor Manuel “Vitu” Giordano

unread,
Feb 6, 2024, 9:42:53 AM2/6/24
to golang-nuts
Hi Goperhs! How you doing? Hope just fine!

I'm wondering why the language allow me to write something like this:

type IncFunc func(a int) int

type Incrementor interface {
IncFunc // <-- THIS is allowed
IncQuantity() int
}



I don't get how I can make leverage of that.. or if has any sense at all 🥴😵‍💫
As I recall an interface is a set of methods, and a method do have a name... the thing here is that the name if the name of the type not the function's name. 

Thanks in advance.
Víctor.



Ian Lance Taylor

unread,
Feb 6, 2024, 10:06:59 AM2/6/24
to Victor Manuel “Vitu” Giordano, golang-nuts
On Tue, Feb 6, 2024 at 6:43 AM Victor Manuel “Vitu” Giordano
<vituc...@gmail.com> wrote:
>
> I'm wondering why the language allow me to write something like this:
>
> type IncFunc func(a int) int
>
> type Incrementor interface {
> IncFunc // <-- THIS is allowed
> IncQuantity() int
> }
>
> (RTR example here)
>
> I don't get how I can make leverage of that.. or if has any sense at all 🥴😵‍💫
> As I recall an interface is a set of methods, and a method do have a name... the thing here is that the name if the name of the type not the function's name.

An interface type like that can be used as a constraint for a type
parameter. It can't be used as the type of a variable. As a type
parameter constraint it means that the type argument must be IncFunc.
It's fairly useless, but follows from the other rules about type
parameter constraints.

Ian

Victor Manuel Giordano

unread,
Feb 6, 2024, 10:28:28 AM2/6/24
to Ian Lance Taylor, golang-nuts
Thanks
--
V
Reply all
Reply to author
Forward
0 new messages