You may use a variadic helper function that accepts any number of arguments. The variadic parameter is treated as a slice inside the function (it is a slice), so you can use it / return it.
This helper is one of the simplest function you can ever write:
func pack(data ...byte) []byte {
return data
}
Testing it:
func one() byte { return 1 }
func two() (byte, byte) { return 1, 2 }
func three() (byte, byte, byte) { return 1, 2, 3 }
func main() {
var data []byte
data = pack(one())
fmt.Println(data)
data = pack(two())
fmt.Println(data)
data = pack(three())
fmt.Println(data)
}
Output (try it on the Go Playground):
[1]
[1 2]
[1 2 3]
Note that the above pack()
function can only be used with functions that return bytes and nothing more. If the functions you want to use it with have other return types too, you may change the type from byte
to interface{}
:
func pack(data ...interface{}) []interface{} {
return data
}
Testing it with these functions:
func one() (byte, int) { return 1, 2 }
func two() (byte, string, interface{}) { return 1, "b", "c" }
func three() (string, byte, error) { return "x", 2, io.EOF }
(and of course using var data []interface{}
)
The output is (try it on the Go Playground):
[1 2]
[1 b c]
[x 2 EOF]
See related question: how to parse multiple returns in golang