Use an arbitrary type struct as function parameter in a golang

Advertisements

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.

>Solution :

use generics

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

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

Leave a ReplyCancel reply