Last active
January 31, 2019 07:50
-
-
Save NaniteFactory/6af38747711efbfa672db8510fbcfd37 to your computer and use it in GitHub Desktop.
Exploding multiple returns to pass to a call to a variadic function.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
func multipleRets() (int, int, int, int) { | |
return 11, 22, 33, 44 | |
} | |
func main() { | |
s1 := append([]int{}, []int{11, 22, 33, 44}...) // This is fine. | |
s2 := append([]int{}, multipleRets()) // But this one errors. | |
s3 := append([]int{}, toSlice(multipleRets())...) // Getting through it. | |
// Abusing much of syntactic sugar we have, | |
// multiple returns of a function can explode to parameters of a variadic function. | |
} | |
// Convert multiple return values to an explodable slice. | |
func toSlice(args ...int) []int { | |
return args | |
} | |
/* | |
https://stackoverflow.com/questions/54424559/how-does-go-determine-the-context-in-which-multiple-values-can-be-used | |
*/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ToSlice is used to combine two different syntactic sugars. | |
// This function with a syntactic sugar can take multiple returns of a call to a function | |
// for its parameters. It then returns a collection of those arguments as a slice, | |
// which again allows the `...` syntactic sugar - exploding a slice to pass its | |
// elements to a variadic function (call). | |
// (Although I'm not sure if this is a good practice or not.) | |
// | |
// E.g. ToSlice(multipleRets())... | |
// | |
func ToSlice(args ...float64) []float64 { | |
return args | |
} | |
// ToSlice with anonymous function. | |
s := func(args ...float64) []float64 { | |
return args | |
}(multipleRets()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment