4. Compound data types

Arrays and structures are aggregate types; Their values consist of the values of many element or member fields. Arrays are made up of isomorphic elements — each array element is of exactly the same type — while structures are made up of heterogeneous elements. Arrays and constructs are data structures with a fixed memory size. Slice and Map, by contrast, are dynamic data structures that grow dynamically as needed.

4.1 an array

An array is a sequence of fixed-length elements of a particular type. An array can consist of zero or more elements. Because arrays are of fixed length, they are rarely used directly in Go. The corresponding type of array is Slice, which can grow and shrink dynamic sequences. Slice is more flexible, but you need to understand arrays to understand how Slice works. Each element of an array can be accessed by index subscripts, which range from 0 to the bits of the array length minus 1. The built-in len function returns the number of elements in the array.

var a [3]int // array of 3 integers
fmt.Println(a[0]) // print the first element
fmt.Println(a[len(a)- 1]) // print the last element, a[2]
// Print the indices and elements.
for i, v := range a {
fmt.Printf("%d %d\n", i, v)
} /
/ Print the elements only.
for _, v := range a {
fmt.Printf("%d\n", v)
}
Copy the code

By default, each element of the array is initialized to the zero value corresponding to the element type, which is 0 for numeric types. We can also initialize an array with a set of values using array literals:

var q [3]int = [3]int{1.2.3}
var r [3]int = [3]int{1.2}
fmt.Println(r[2]) / / "0"
Copy the code

In an array literal, if “… “appears at the length of the array. Ellipsis indicates that the length of the array is calculated based on the number of initialized values. Therefore, the definition of the q array above can be simplified as

q := [...]int{1.2.3}
fmt.Printf("%T\n", q) // "[3]int"
Copy the code

The length of an array is a component of the array type, so [3]int and [4]int are two different array types. The length of the array must be a constant expression, because the length of the array needs to be determined at compile time.

q := [3]int{1.2.3}
q = [4]int{1.2.3.4} // compile error: cannot assign [4]int to [3]int
Copy the code

We’ll see that arrays, slices, maps, and struct literals are all written similarly. The above form provides a sequence of values directly, but it can also be initialized by specifying an index and a list of values, as follows:

type Currency int
const (
USD Currency = iota / / $
EUR / / euro
GBP / / the pound
RMB / / yuan
) s
ymbol := [...]string{USD: "$", EUR: "Which", GBP: "On", RMB: "RMB"}
fmt.Println(RMB, symbol[RMB]) 3 RMB "/ /"
Copy the code