how to make a function to return a generic of struct?

Issue

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

Solution

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

Answered By – icza

Answer Checked By – Katrina (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.