Home  >  Article  >  Backend Development  >  Golang: Access fields on "any" type generic

Golang: Access fields on "any" type generic

WBOY
WBOYforward
2024-02-10 10:39:07884browse

Golang: Access fields on any type generic

Golang is a statically typed programming language that has always attracted much attention in the process of implementing generics. Recently, the Golang team has made a major breakthrough in designing generics, allowing developers to access fields on "any" type generics. This new feature brings greater flexibility and scalability to Golang. Next, we will let PHP editor Xigua introduce to you in detail the methods and application scenarios of accessing fields on "any" type generics in Golang.

Question content

I am using a third party function whose generic type is any. The function returns an object of the type passed to it, and my own code works against that return.

I'm trying to write my own generic function that accepts a generic of type HasID and then passes it to a third party function. However, when I try to access the ID field of the third party function's return value, I get an error.

What do I need to do to enter this correctly?

type HasID struct {
    ID string `json:"id"`
}

func ThirdPartyFunc[T any]() T {
  // do some stuff
  return someThing // of type T
}

func MyFunc[U HasID]() {
  thingWithID := ThirdPartyFunc[U]()
  fmt.Println(thingWithID.ID) // undefined (type U has no field or method ID)
}

Workaround

I agree with @mkopriva's comment, but I think it might be because you "can't" define the fields on the constraint, so you can't access those fields in the type parameters.

(Probably not changed in Go 1.19, haha)

To keep things simple, just do as you would:

type HasID struct {
    ID string `json:"id"`
}

func MyFunc[U HasID](hasID U) {
    fmt.Println(hasID.ID) // hasID.ID undefined (type U has no field or method ID)

}

https://www.php.cn/link/bddcda5d65fcfdec9de3838794a77265

But if you define it as an interface, you will have access to its methods:

type HasID interface {
    ID() string
}

func MyFunc[U HasID](hasID U) {
    fmt.Println(hasID.ID()) // compiles V
}

https://www.php.cn/link/46dfb1fd21d4e16401260f54d2b6a88a

In order to handle the structure, you need to do some type conversion:

type HasID struct {
    ID string `json:"id"`
}

func MyFunc[U HasID](hasID U) {
    thingWithID := HasID(hasID)
    fmt.Println(thingWithID.ID)
}

P.S - There is an open issue from 02/2022 - https://github .com/golang/go/issues/51259

P.S - Oh, I just found out... - How to access structure fields using generics (type T has no fields or methods)?

The above is the detailed content of Golang: Access fields on "any" type generic. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete