Function type is useful:
- In the case of higher-order functions as we have seen in the above example. The argument and return type is specified using function type
- In the case of defining interfaces in go as in the interface, only the function type is specified. Whatever implements this interface has to define a function of the same type
Notice that the interface shape only defines the type of function
package main
import "fmt"
func main() {
var shapes []shape
s := &square{side: 2}
shapes = append(shapes, s)
r := &rectangle{length: 2, breath: 3}
shapes = append(shapes, r)
for _, shape := range shapes {
fmt.Printf("Type: %s Area: %d\n", shape.getType(), shape.area())
}
}
func sum(a, b int) int {
return a + b
}
type shape interface {
area() int
getType() string
}
type rectangle struct {
length int
breath int
}
func (r *rectangle) area() int {
return r.length * r.breath
}
func (r *rectangle) getType() string {
return "rectangle"
}
type square struct {
side int
}
func (s *square) area() int {
return s.side * s.side
}
func (s *square) getType() string {
return "square"
}
Output:
Type: square Area: 4
Type: rectangle Area: 6
A function that can accept a dynamic number of arguments
func add(numbers ...int)
here is the example:
package main
import "fmt"
func main() {
fmt.Println(add(1, 2))
fmt.Println(add(1, 2, 3))
fmt.Println(add(1, 2, 3, 4))
}
func add(numbers ...int) int {
sum := 0
for _, num := range numbers {
sum += num
}
return sum
}
Output:
3
6
10