Skip to content

Commit ab91f19

Browse files
committed
Variadic Interface Functions
1 parent a426ee3 commit ab91f19

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

variadic_functions/main.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package main
2+
3+
import "fmt"
4+
5+
// Unpack operator breaks a slice into individual components. it ends with ... like slice...
6+
// Pack operator combine individual elements like integers into a slice. It starts with ... like ...Type
7+
// Effective Go talks about append but wish it would spend just a bit more time on the subject.
8+
9+
var exNum int
10+
11+
func main() {
12+
13+
variadicA([]string{"a", "b", "c"}...)
14+
variadicA("d", "e", "f")
15+
16+
// The mythical variadic interface{}
17+
variadicInterface(1.0, "a", 2, []int{1, 2})
18+
19+
}
20+
21+
func variadicA(elems ...string) {
22+
exNum++
23+
fmt.Printf("Example number: %d", exNum)
24+
str := ""
25+
for _, e := range elems {
26+
str += e
27+
}
28+
fmt.Println("Output: ", str)
29+
}
30+
31+
func variadicInterface(elems ...interface{}) {
32+
exNum++
33+
fmt.Printf("Example number: %d", exNum)
34+
for _, e := range elems {
35+
switch e.(type) {
36+
case float64:
37+
fmt.Println("Type is float64")
38+
case int:
39+
fmt.Println("Type is Integer")
40+
case string:
41+
fmt.Println("Type is String")
42+
case []int:
43+
fmt.Println("Type is []int")
44+
default:
45+
fmt.Printf("Catch-all. Type is %T", e)
46+
}
47+
}
48+
}

0 commit comments

Comments
 (0)