Details of Golang array delivery

  • 2020-06-19 10:32:17
  • OfStack

The concept is introduced

Arrays and slices

An array is a sequence of 1 numbered, fixed-length data items of the same unique type. The maximum length of the array is 2Gb, which is the value type. A slice is a reference to a contiguous fragment of an array, so a slice is a reference type.

Pass by value and pass by reference

There are two ways to pass arguments to functions in Go: by value and by reference. By default, Go passes parameters by value, which is a copy of the parameters passed. Changing the value of the copy in a function does not affect the original variable.

Passing by reference is also called passing by value, except that the copy is a copy of the address to which the value points.

In Go, reference types (slice, map, interface, channel) are passed by default when a function is called.

Disadvantages when passing arrays

In general, passing a pointer consumes less than passing a copy, especially if the array is extremely large. Specific reasons are as follows:

Value passing requires a full copy of the initial array and placing the copy on the stack, which is time-consuming and inefficient. The copy of the original array requires additional memory space (memory in the stack) The compiler needs to produce a special section of code to copy the initial array, which will make the program larger.

How to avoid

As described above, there are two methods. The first method USES Pointers, which are passed by reference. The second USES a slice, which is a reference type and is passed by reference by default.

Use Pointers for passing


package main
import "fmt"
func main() {
  var arr = [5]int{1, 2, 3, 4, 5}
  fmt.Println(sum(&arr))
}
func sum(arr *[5]int) int {
  s := 0
  for i := 0; i < len(arr); i++ {
    s += arr[i]
  }
  return s
}

Use slices for passing


package main
import "fmt"
func main() {
  var arr = [5]int{1, 2, 3, 4, 5}
  fmt.Println(sum(arr[:]))
}
func sum(arr []int) int {
  s := 0
  for i := 0; i < len(arr); i++ {
    s += arr[i]
  }
  return s
}

The last one is often used.

Refer to the article

1. the way to go

conclusion


Related articles: