This article is typographically incorrect: please go to “here” for a better read

Slice and array definitions and differences

  • An array of

An array is a sequence of fixed-length elements of a particular type. An array can consist of zero or more elements.

  • slice

Slice represents a variable-length sequence in which each element has the same type. A slice type is written as []T, where T stands for the type of the slice element; Slice’s syntax is similar to that of an array, except that there is no fixed length.

type slice struct {
    array unsafe.Pointer
    len   int
    cap   int
}
Copy the code

See the structure of slice, Pointers, length (len), and capacity (CAP).

  • Difference between contrast

Biggest difference: Variable slice length

Difference between contrast

An array of

slice

The length of the

fixed

variable

The element type

Single and fixed

Single and fixed

Constituent parts

A series of elements

Pointers, Length (len), and capacity (Cap) (underlying reference to an array object)

Pointer to

Points to the address of the first element of the array

The address that points to the underlying array element corresponding to the first slice element. Note that the first slice element is not necessarily the first array element

Initialize the

The default value is zero, and the initial length is required

The default value is zero, and no initialization length is required

Slice and array FAQs and precautions

  • How do I distinguish “array” from “Slice”?

    • Var arr1 []int, without length definition, is Slice and nil Slice

    • Arr2 := make([]int, 5), make must define slice

    • Arr3 := []int{}, without length definition, is Slice

    • Var arr4 [5]int, Array if length is defined

  • Arrays require an initial length to be usable

    Var arr1 [5]int arr2 := […] Int {1,2,3,4,5} // after the data is defined, the length of arr2 is fixed at 5

  • How do I determine if Slice is empty? (Slice void)

Never use if slice == nil

Because you can create nil slices

  • Correct method:len(slice) == 0

Empty slice vs. nil slice, deep understanding why slice == nil is not feasible

var s1 []int // nil slice

s2 := []int{} // empty slice

infrastructure

nil slice

empty slice

array

0

0x6736adb0

Len

0

0

Cap

0

0

Compared with nil

True

False

However, the official advice is to use it whenever possiblenilslice

  • **Slice copy pit **

S2 := s1[:]; s2 := s1[:]; s2 := s1[:]; s2 := s1[:]

  • Arrays can be used= =To compare, butsliceno

When to use Slice? When to use arrays?

Use an array

  • When the length of the data is known, there is no need to change the length

Using Slice

  • The length is unknown and needs to change dynamically