Skip to content

Instantly share code, notes, and snippets.

@tokhi
Last active July 3, 2023 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tokhi/e9eb24b35c5832b3869d8e512a4aad9e to your computer and use it in GitHub Desktop.
Save tokhi/e9eb24b35c5832b3869d8e512a4aad9e to your computer and use it in GitHub Desktop.
Go Tutorial

Go Tutorial

Function Types

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

Variadic Function

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment