Embedding any (empty interface) in a struct in Go

172 views
Skip to first unread message

sick...@gmail.com

unread,
Oct 26, 2022, 3:17:50 PM10/26/22
to golang-nuts

Consider a scenario where you want to embed an error within any type of variable.

This can be achieved by embedding any in a struct and it seems to be a valid syntax in Go 1.9.

    type WithError struct {
        any
        err error
    }
    func main() {
        a := WithError{ any: 5, err: nil, }
        fmt.Printf("%+v\n", a)
    }

Does this violate any community best practices?
Is there an alternative pattern that can achieve a similar result?

Axel Wagner

unread,
Oct 26, 2022, 4:10:32 PM10/26/22
to sick...@gmail.com, golang-nuts
On Wed, Oct 26, 2022 at 9:17 PM sick...@gmail.com <sick...@gmail.com> wrote:

Consider a scenario where you want to embed an error within any type of variable.

This can be achieved by embedding any in a struct and it seems to be a valid syntax in Go 1.9.

    type WithError struct {
        any
        err error
    }

I don't think this really "embeds an error within any type of variable". It *groups* an error with a value of any type. If anything is embedded, it's `any` though.
 

Does this violate any community best practices?
Is there an alternative pattern that can achieve a similar result?

I don't think it violates any best practices. I would find it slightly confusing and wonder why you didn't do
type WithError struct {
    value any
    err error
}
which seems clearer and mostly has the same effect - the embedding of `any` doesn't really do anything, as it has no methods and is an unexported name.

I also think this seems probably more handy:
type WithError[T any] struct {
    value T
    err error
}

But, really, while I don't really understand what you are trying to accomplish, there's nothing wrong with your code.

 

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/0a6bbea5-c37b-4ce4-89d6-2b44d7868639n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages