Interface Fields

125 views
Skip to first unread message

Dave Protasowski

unread,
Jan 12, 2021, 8:34:00 PM1/12/21
to golang-nuts
I'm doing some due-diligence and wondering if there's any old topics about extending interfaces to support field sets.

ie.
type WithID interface {
   ID string
}
type X struct { ID string }
type Y struct { ID string }
func PrintID(item WithID) {
  fmt.Println(item.ID)
}

In the above the PrintID function only accepts structs with a field named `ID` - which X & Y satisfy. This is sort of like duck typing but with fields.

I've found https://groups.google.com/g/golang-nuts/c/18gH5TR_3ZE/m/9dyyT4veBgAJ but I don't know the discussion the person was referencing and it seems specific to generics.

thanks,
dave

Henry

unread,
Jan 12, 2021, 10:04:58 PM1/12/21
to golang-nuts
I remember reading some proposals about it somewhere, either here at golang-nuts or at github. The general consensus was no, because interface is all about behavior. Struct is for data and interface is for behavior, or something like that if I remember it correctly. 

In your specific example, since PrintID requires only the ID field, you can refactor it into something like this:
```
func Print(str string) {
   fmt.Println(id)
}

Print(x.ID) 
Print(y.ID)
```
I hope it helps.

Henry

Dave Protasowski

unread,
Jan 13, 2021, 12:34:27 AM1/13/21
to Henry, golang-nuts

--
You received this message because you are subscribed to a topic in the Google Groups "golang-nuts" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/golang-nuts/TrqgBPzyk54/unsubscribe.
To unsubscribe from this group and all its topics, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/f4dee908-b4ac-4661-9356-8850a7292c10n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages