Golang array transfer details

Concept introduction

Arrays and slices

An array is a numbered, fixed-length sequence of data items of the same unique type. The array length is up to 2Gb and it is a value type. A slice is a reference to a contiguous piece of an array, so a slice is a reference type.

Pass-by-value and pass-by-reference

There are two ways to pass parameters of functions in Go language, pass-by-value and pass-by-reference. Go uses pass-by-value by default to pass parameters, that is, passing a copy of the parameter. Changing the value of the copy in the function does not affect the original variable.

Pass-by-reference can also be called "pass-by-value", except that the copy is a copy of an address through which the value at the address pointed to by the value can be modified.

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

Disadvantages of array passing

In general, passing a pointer is less expensive than passing a copy, especially when the array is particularly large. The specific reasons are:

  • Pass-by-value requires a complete copy of the initial array and puts the copy on the stack, which takes a lot of runtime, so the pass-by-value method is inefficient.
  • The copy of the initial array requires additional memory space (memory on the stack)
  • The compiler needs to specifically generate a portion of the code to copy the initial array, which makes the program larger.

how to avoid

As described above, there are two methods, the first uses pointers, that is, pass by reference; the second uses slices, because slices are reference types, and pass by reference is used by default.

pass by pointer

1

2

3

4

5

6

7

8

9

10

11

12

13

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 delivery

1

2

3

4

5

6

7

8

9

10

11

12

13

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 method is usually more common.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324134991&siteId=291194637