This is the seventh day of my participation in the August More text Challenge. For details, see:August is more challenging

What is a function

A function is a block of code that performs a specific task. In Go, functions are first-class citizens, and the main function is the entry point for the Go program, but the main function cannot be called.

Declaration of functions

The Go language has at least one main function

Syntax format:

func funcName(parametername type1, parametername type2) (output1 type1, output2 type2) {
  // Here is the processing logic
  // Return multiple values
  return value1, value2
}
Copy the code
  • Func: A function is declared beginning with func
  • FuncName: The name of a function, which together with the argument list constitutes a function signature.
  • Parametername type: list of parameters. Parameters act as placeholders. When a function is called, you can pass values to the parameters. The parameter list specifies the parameter type, order, and number of parameters. Arguments are optional, which means the function can contain no arguments.
  • Output1 type1, outpuT2 type2: Return types. The function returns a list of values. Return_types is the data type of the column values. Some functions do not require a return value, in which case return_types is not required.
  • The above return value declares two variables output1 and output2. If you don’t want to declare them, just two types.
  • If there is only one return value and no return value variable is declared, then you can omit the parentheses containing the return value (i.e. a return value may not declare a return type).
  • Function body: The set of code defined by a function.

Use of functions

Example code:

package main

import "fmt"

func main(a) {
   /* Define local variables */
   var a int = 100
   var b int = 200
   var ret int

   /* Call the function and return the maximum */
   ret = max(a, b)

   fmt.Printf( "Maximum value: %d\n", ret )
}

/* The function returns the maximum value of two numbers */
func max(num1, num2 int) int {
   /* Define local variables */
   var result int

   if (num1 > num2) {
      result = num1
   } else {
      result = num2
   }
   return result 
}
Copy the code

Running result:

The maximum is:200
Copy the code

Parameter of a function

Use of parameters

Formal parameters: When defining a function, they are used to receive data from outside. They are called formal parameters, or parameters for short.

Actual arguments: The actual data passed to a parameter when a function is called is called the actual arguments.

Function call:

A: The function name must match

B: Real participation parameters must correspond to each other: order, number, type

The variable parameter

The Go function supports variational parameters. A function that takes a variable parameter has an indefinite number of parameters. To do this, we first need to define a function that accepts a variable parameter:

func myfunc(arg ...int) {}
Copy the code

arg … Int tells Go that this function takes an indefinite number of arguments. Note that all of these arguments are of type int. In the body of the function, the variable arg is a slice of an int:

for _, n := range arg {fmt.Printf("And the number is: %d\n", n)}
Copy the code

Example code:

package main

import "fmt"

func main(a) {
    /* Variable arguments: If a function has an argument of a certain type but an uncertain number, use variable arguments. Number: 0- Multiple syntax format: Variable-parameters: Parameter name... A: A function can take at most one parameter. B: If there are other parameters in the parameter list than the mutable parameters, write the mutable parameters at the end. * /
    r1 := getSum(1.2)
    fmt.Println(r1)
    r2 := getSum(1.2.3.4.5)
    fmt.Println(r2)

    //Println(), whose arguments are mutable parameters
    fmt.Println(1.2.3.4.5.6)
    s1 := make([]int.3.10) // Create a slice with length 0 and capacity 10.
    fmt.Println(s1)
    // Append (), which can add multiple data to the slice
    s1 = append(s1, 1.2.3.4)
    fmt.Println(s1)

    s2 := []int{7.8.9}
    s1 = append(s1, s2...)
    fmt.Println(s1)

    s3 := [] int{1.2.3.4.5.6.7.8.9.10}
    r3 := getSum(s3...)
    fmt.Println(r3)

}

// Sum of 0- multiple int values.
func getSum(nums ... int) int {
    //fmt.Printf("%T\n",nums)
    sum := 0
    for i := 0; i < len(nums); i++ {
        sum += nums[i]
    }
    return sum
}
Copy the code

Running result:

3151 2 3 4 5 6[0 0 0][0 0 0 1 2 3 4][0 0 0 1 2 3 4 7 8 9]55
Copy the code

Parameter passing

The parameters of go functions are also passed by value and by reference

Function application scenario

Value passed

package main

import (
   "fmt"
   "math"
)

func main(a){
   /* Declare a function variable */
   getSquareRoot := func(x float64) float64 {
      return math.Sqrt(x)
   }

   /* Use the function */
   fmt.Println(getSquareRoot(9))}Copy the code

reference

This involves something called a pointer. We know that variables are stored at certain addresses in memory, and modifying variables is actually modifying the memory at the address of variables. The value of the x variable can be changed only if the add1 function knows the address of the x variable. In order to change the value of the x variable in the function, we need to pass the address &x into the function and change the type of the argument from int to *int. The argument is still passed by copy, but the copy is a pointer.

package main
import "fmt"
// A simple function that implements the operation of parameter +1
func add1(a *int) int { // Please note,
	*a = *a + 1 // Change the value of a
	return *a   // Return the new value
}
func main(a) {
	x := 3
	fmt.Println("x = ", x)    // should print "x = 3"
	x1 := add1(&x)            // Call add1(&x) to pass the address of x
	fmt.Println("x+1 = ", x1) // output "x+1 = 4"
	fmt.Println("x = ", x)    // should print "x = 4"
}
Copy the code
  • Passing Pointers enables multiple functions to operate on the same object.
  • Pointer passes are lightweight (8bytes) and only pass memory addresses. We can pass large structures with Pointers. If passed by parameter values, there is a relatively high overhead (memory and time) on each copy. So it’s wise to use Pointers when passing large structures.
  • Slice and Map are implemented like Pointers in Go, so you can pass it directly instead of passing the pointer after you take the address.If the function changes the length of slice, it still needs to take the address pass pointer

Example code:

package main

import "fmt"

func main(a)  {
    /* Pass parameters: data type: value type, reference type. Value type: A copy of the value is passed. If passed as a parameter, it is passed by value. Base types: int, Float64, String Array: Reference type: address of the data passed. If passed as an argument, it is passed by reference. Slice slice, map map */
     a := 1
     b := 2
     fmt.Printf("A: %d, b: %d\n",a,b) / / 1, 2
     fun3(a,b)
     fmt.Printf("A: %d, b: %d\n",a,b)/ / 1, 2

     //2. Array as parameter, value passed
     arr1 :=[4]int{1.2.3.4}
     //arr3 := arr1 // assign a copy of the data in arR1 to arr3
     fmt.Println(arr1) / / [1, 2, 3, 4]
     fun4(arr1)
     fmt.Println(arr1)/ / [1, 2, 3, 4]

     //3. Slice as parameter
     s1 :=[] string{"Zhang"."Bill"."Fifty"}
     //s3 := s1 // assign the value in s1 to s3
     fmt.Println(s1)
     fun5(s1)
     fmt.Println(s1)
}
// Accept two integers as arguments
func fun3(m, n int){
    fmt.Printf("M: %d, n: %d\n",m, n)/ / 1, 2
    m = 100
    n = 200
    fmt.Printf("Function: m: %d, n: %d\n",m,n) // 100,200
}
// Receive an array as an argument
func fun4(arr2 [4]int){ // arr2 = arr1
    arr2[0] = 100
    fmt.Println(arr2) / / (100, 2, 3, 4)
}
// Accept slice as parameter
func fun5(s2 [] string){ //s2 = s1
    s2[0] = "The Great Sage"
    fmt.Println(s2)
}
Copy the code

The return value of the

What is the return value of a function

After a function is called, it returns the result of its execution at the place where it was called, called the return value of the function.

The result needs to be received at the call using a variable

A function can return multiple values

A function can have no return value, one return value, or multiple returns.

package main

import "fmt"

func swap(x, y string) (string.string) {
   return y, x
}

func main(a) {
   a, b := swap("Mahesh"."Kumar")
   fmt.Println(a, b)
}
func SumAndProduct(A, B int) (add int, Multiplied int) {
    add = A+B
    Multiplied = A*B
    return
}
Copy the code