Skip to content

Instantly share code, notes, and snippets.

@humamfauzi
Created August 8, 2018 05:41
Show Gist options
  • Save humamfauzi/00828baee80475d3bd9bdf884ab0cba7 to your computer and use it in GitHub Desktop.
Save humamfauzi/00828baee80475d3bd9bdf884ab0cba7 to your computer and use it in GitHub Desktop.
Example using triple dots (variadic parameter) in Golang
package main
import "fmt"
// If function want to take any dtype, use interface{}. We can iterate it using for range
func threeDotsInterface(a ...interface{}) {
for k, v := range a {
fmt.Println("Key ", k, " Value ", v)
}
}
// Same as above, but only apply for interface{}
func squareBracketInterface(a []interface{}) {
for k, v := range a {
fmt.Println("Key ", k, " Value ", v)
}
}
func threeDotsStr(a ...string) {
for k, v := range a {
fmt.Println("Key ", k, " Value ", v)
}
}
// ...string can be replaced with ...interface{} for more flexible input
func mixThreeDots(a, b int, c ...string) {
fmt.Println("Sum of two int: ", a + b)
for k, v := range c {
fmt.Println("Key ", k, " Value ", v)
}
}
func main() {
threeDotsInterface(1, 2.5, "foo", []int{2,3}, false)
squareBracketInterface([]interface{}{1, 2.5, "foo", []int{2,3}, false})
threeDotsStr("foo", "baar", "another foo")
mixThreeDots(3, 4, "another", "string", "for", "the", "test")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment