Home > OS >  how to make a function to return a generic of struct?
how to make a function to return a generic of struct?

Time:02-01

I'm learning genric in go. I have struct User and Member, and I want to make a function to return User or Member. How I can achieve this?

edit: I don't want to use interface{} or any

CodePudding user response:

interface{} has always been an eyesore in Go - so Go 1.18 (with Generics support) you can now use the new keyword any for any type:

func myFunc[T any](in T) (out T) {
    // do stuff
    return
}

or you can use a targeted subset of types as @icza outlines User | Member

https://go.dev/play/p/RGm6cl4ncqA?v=gotip

CodePudding user response:

You may use interface{} result type, so you can return any value (also not just User and Member). You may use 2 return values (Go allows that). Or use 2 different functions.

If you want to do it using generics, this is how it could look like:

func getSomething[T User | Member]() T {
    var result T
    return result
}

getSomething() has a type parameter that allows User or Member.

This is how you could call it:

fmt.Printf("%T\n", getSomething[User]())
fmt.Printf("%T\n", getSomething[Member]())

Which outputs (try it on the Go Playground):

main.User
main.Member
  •  Tags:  
  • Related