Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use an arbitrary type struct as function parameter in a golang

I want to pass an arbitrary type-struct to a function in golang, like this:

func Function(t) {
    var VariableOfTypeT t
    var SliceOfTypeT []t
}

I don’t know what type use for t, I tried to use interface{} like this:

func Function(t interface{}) {
    var VariableOfTypeT t
    var SliceOfTypeT []t
}

But it doesn’t work, It says t (variable of type interface{}) is not a type.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

use generics

func Func[t any](req t) t {
    return req
}

func TestA(t *testing.T) {
    fmt.Println(Func[int](1))
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading