[Golang] Function, closure, method

Tags
Golang
Engineering
Created
Nov 7, 2023 04:52 AM
Edited
Nov 6, 2023
Description

Function

// entry point
func main() {
	fmt.Println("Hello World!")
}

// normal function
func sum (x int, y int) int {
	return x + y
}
  • If there are too many return values, you can return an output object and an error (same as input)
func (c *DynamoDB) CreateTable(input *CreateTableInput) (*CreateTableOutput, error)
  • Try to name result parameters for better documentation
func ReadFull(r Reader, buf []byte) (n int, err error) {
    for len(buf) > 0 && err == nil {
        var nr int
        nr, err = r.Read(buf)
        n += nr
        buf = buf[nr:]
    }
    return
}

Closure

💡
A closure is a function value that references variables from outside its body.
// closure
func adder() func(int) int {
	sum := 0
	// return a closure
	return func(x int) int {
		sum += x
		return sum
	}
}

Method

// method
/* define a circle */
type Circle struct {
   x,y,radius float64
}

/* define a method for circle */
func(circle Circle) area() float64 {
   return math.Pi * circle.radius * circle.radius
}

// can be used on non-struct types
type MyFloat float64

func (f MyFloat) Abs() float64 {
	if f < 0 {
		return float64(-f)
	}
	return float64(f)
}

Source

https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/#DynamoDB.CreateTable
Â