Search code examples
gostructfunc

Go Pass Func to Struct like fields, Error "too few values in struct literal of type Test"


type Test struct {
    a int
    b int
}

func f(a, b int) (int, int) {
    return a, b
}

k := Test{(f(5, 6))} // Error

but

type Test struct {
    a int
}

func f(a int) int {
    return a
}

k := Test{(f(5))} // Ok

How send func result to struct fields, or create method for group of types, example:

 func(MyType1, MyType2) f (something) something {}

Solution

  • Even though your function in the first example returns two values, the language specification does not provide a mechanism to distribute multiple return values to implicit fields automatically; you must be explicit.

    The simplest way to do this in your first example would be:

       t := Test{}
       t.a, t.b = f(a, b)
    

    Your second question is not entirely clear.

    You could mean something similar to:

       func(values ...int) func(...int) []int
    

    i.e. a function accepting a variable number of int arguments, returning a function that also accepts a variable number of int arguments and returns a slice of int.

    There is no way to return a variable number of values, other than as a slice.

    If the arguments are required to be of (potentially) different types, then you would need to use the any type:

       func(values ...any) func(...any) []any
    

    If you had a specific case where you want two distinct, explicit types in the initial function, then you must be specific about the number and order of those values; when it comes to the return value of the returned function you would again need to resort to any:

       func(v1 int, v1 string) func(int, string) []any
    

    A generic function which could accept two values of any type, where those types are to be specified at the call site, is just a generic [sic] form of the previous case:

       func[T1 any, T2 any](v1 T1, v2 T2) func(T1, T2) []any
    

    Similarly, a generic function could be used for the initial example of 0..n values of a given type:

       func[T any](values ...T) func(...T) []T
    

    Note that the any constraint on the types in these generics may not be appropriate in your specific use case. There is insufficient information to suggest a more appropriate constraint.

    I hope that answers your question. If not, you'll need to provide more information about what you are trying to achieve.