function

A function is a basic block of code that is used to reuse code that needs to be executed repeatedly. In GO, functions are “first-class citizens”, which is similar to JS in that functions can be passed as a variable.

Function declaration

Because it is a strongly typed language, unlike JS, you need to specify the types of parameters and return values during function declaration.

func max (n1, n2 int) int {
  var result int
  if n1 >= n2 {
    result = n1
  }
  if n1 < n2 {
    result = n2
  }
  return result
}
Copy the code

When declaring function parameters and types, similar to declaring variables, you can specify the types of multiple parameters at one time or specify multiple parameters as different types.

func max (n1 int, n2 int) int {
  ……
}
Copy the code

If a function returns multiple values, specify the type of each return value.

func max (n1 int, n2 int) (error, int){...return errors.New(""), result
}
Copy the code

In the above code, two values are returned. The first value is an error object, which indicates whether an exception occurred during execution. This is also common in Node.js for error-first callback.

Special function

In GO, there are two special functions: main and init. After these two functions are declared, they generally do not need to be called actively, but will be executed automatically.

🔎 func main ()

The main function is the default entry function in the GO language and can only be used in package Main if it is not executed in any other package. The main function has the following points to note:

  • Cannot define parameters;
  • Cannot define a return value;
  • Must be inpackage mainIn the statement;

🔎 func init ()

The init function is executed before main when all packages are started. Like main, it cannot define parameters or return values.

package main

import "fmt"

func init(a) {
	fmt.Println("Execute init function \n")}func main(a) {
	fmt.Println("Execute main function \n")}Copy the code

A function call

Function calls are relatively simple, similar to other programming languages. You only need to pass in the parameters that the function needs to accept, and then get the corresponding return value after execution.

// Define the Max function
func max (n1, n2 int) int {
  var result int
  if n1 >= n2 {
    result = n1
  }
  if n1 < n2 {
    result = n2
  }
  return result
}

func main (a) {
	var result = max(5.100)
	fmt.Println("max return", result)
}
Copy the code

Anonymous functions

An anonymous function is a function that has no defined function name. An anonymous function can be assigned to a variable as if it were a value. This is why functions are “first-class citizens”, that is, functions can be treated as a variable.

var max = func (n1, n2 int) int {
  var result int
  if n1 >= n2 {
    result = n1
  }
  if n1 < n2 {
    result = n2
  }
  return result
}
var result = max(5.100)
fmt.Println("max return", result)
Copy the code

Execute function immediately

Since the function in GO is a “first-class citizen”, it can be executed immediately after the declaration, that is, after the declaration, a parenthesis is added directly to indicate that the function will be executed immediately, and the result after execution can be received through variables.

import "math"

var Pi = func (a) float64 {
  return math.Pi
}()

fmt.Println("PI =",Pi)
Copy the code

closure

Closures are functions that can read variables inside other functions. In essence, closures are Bridges that connect the inside and outside of a function. — Baidu Encyclopedia

The above description is from Baidu Encyclopedia. It is difficult to understand the concept for the first time. From the perspective of use, closure is to return another anonymous function after a function call, and keep the local variables in the current function, which can be referenced to the anonymous function.

We can simply implement an iterator function that takes a slice and returns an anonymous function that fetches one value of the slice each time it is executed until it has all been read.

func generate(slice []int) func(a) (bool.int) {
	i := 0
	length := len(slice)
	return func (a) (bool.int) {
		if i >= length {
			return true.0
		}
		var result = slice[i]
		i++
		return false, result
	}
}

func main(a) {
	slice := []int{1.2.3.4.5}
	nextNum := generate(slice)
	done, result := nextNum()
  // Stop until done does not equal false
	for done == false {
		fmt.Println(result, done)
		done, result = nextNum()
	}
  fmt.Println(result, done)
}
Copy the code

Pointer to the

A variable is usually a value, and a pointer points to the location in memory where the variable is stored. Pointers can also be stored in a variable called a pointer variable.

Pointer variable declaration

When declaring a pointer variable, you need to know which type the pointer points to. Because different types of values take up different amounts of memory, it is not enough to know the memory address. You also need to know how much memory the variable takes up. To declare a pointer variable, simply prefix the type with *.

var point *int // Declare a pointer of type int
Copy the code

Pointer variable assignment

To assign a value to a pointer variable, you need to add an ampersand before the variable of the corresponding type to indicate the address of the variable.

var i = 1
var point *int
point = &i
Copy the code

Value passing and reference passing

Normally, the parameters we pass to a function are only the values of the variables. Such passing is called value passing, and changes to the parameters inside the function do not affect the external variables.

func addOne(slice []int, number int) {
	slice = append(slice, number)
	fmt.Println("inner slice =",  slice)
}

slice := []int{1.2.3}
addOne(slice, 100)
fmt.Println("outer slice =",  slice)
Copy the code

In the above code, we wrote a function that appends a value to the passed slice, and when we call it, we see that the value of the external slice is not variable.

If you want the value of an external variable to change with the function call, you need to pass a pointer to the variable into the function. Such passing is called passing by reference. Modifying parameters in a function can affect external variables.

// Slice is a pointer variable
func addOne(slice *[]int, number int) {
  // The slice pointer can be retrieved by *slice
	*slice = append(*slice, number)
	fmt.Println("inner slice =",  *slice)
}

slice := []int{1.2.3}
addOne(&slice, 100)
fmt.Println("outer slice =",  slice)
Copy the code