This is the fourth day of my participation in Gwen Challenge

Second, golang composite data type special

Complex data types are also constructed from basic quantity types, including array, slice, map, and struct. Arrays and structures are data structures with a fixed memory size. Slice and Map, by contrast, are dynamic data structures that grow dynamically as needed.

An array of 1.

Array definition defines and initializes an array whose length is fixed, constant, and determined at compile time.

var q [3]int = [3]int{1, 2, 3} q := [...] Int {1, 2, 3} // or through... Place, automatically calculate the numberCopy the code

Range can be used to iterate over the index and value of the number group.

var a [3]int 
for index, value := range a {
    fmt.Printf("%d %d\n", index, value)
}

// Get value only
for _, value := range a {
    fmt.Printf(""%d\n", value)
}
Copy the code

Passing an array to a function does not allow you to modify the elements of the underlying array inside the function.

main(){
	num := [3]int{1.2.3}
	myInt := 100
	changeNum(myInt, num)
	fmt.Println(num[0], myInt)

}
func changeNum(myInt int, num [3]int) {
	num[0] = 0
	myInt++
}
//output
1 100
Copy the code

We pass in a changeNum function with a variable and an array, and the underlying array data is not modified. Function parameter variables in Golang receive a copy, not the original called variable. If you want to modify the underlying array data through an array you can pass in an array pointer just like in any other language.

main(){
	num := [3]int{1.2.3}
	changeNumPoint(&num)
	fmt.Println(num[0])}func changeNumPoint(num *[3]int) {
	num[0] = 0
}
//output
0
Copy the code

2.slice

Slice creates an array of the appropriate size, and a pointer to slice points to the underlying array.

Slice internal structure

struct    Slice
    {    
        byte*    array;        // actual data
        uintgo    len;        // number of elements
        uintgo    cap;        // allocated number of elements
    };
Copy the code

The first pointer points to the underlying array, followed by the length and size of slice. At the bottom, make creates an anonymous array variable and returns a slice; The underlying anonymous array variable can only be referenced through the returned slice. We can create slice using built-in make.

Make ([]T, len, cap) //cap saves lenCopy the code

Slice length: number of elements in a slice.

Slice size: the number of slices counted from its first element to the end of its underlying array element. When append is used to add data, the size is automatically doubled if it is smaller than the length.

The slice value contains a pointer to the first slice element, so passing slice to a function allows you to modify the elements of the underlying array inside the function, which is passed in as a copy.

main(){
	sliceNum := []int{4.5.6}
	changeSlice(sliceNum)
	fmt.Println(sliceNum[0]}func changeSlice(sliceNum []int) {
	sliceNum[0] = 0
}
//output
0
Copy the code

Append multiple elements with append:

x = append(x, 4, 5, 6)
Copy the code

Copy (dest, SRC) indicates peer replication.

slice1 := []int{1, 2, 3, 4, 5}
slice2 := []int{6, 7, 8}
copy(slice2, slice1)
Copy the code

3.Map

Hash table, similar to the DIC dictionary in Python, map is an unordered collection of key/value pairs.

As with slice, you can create a map using make, or traverse through range:

ages := make(map[string]int){"key":value}
Copy the code

Accessing a map with key as an index subscript produces a value. If the key exists in the map, the value corresponding to the key is obtained. If key does not exist, then you get zero for the type of value. We can use this value to determine whether the value of the key index exists.

age, ok := ages["key"]
if! ok { ... }// Can be optimized to
if age, ok := ages["bob"]; ! ok { ... }Copy the code

The comparison of the map

func equal(x, y map[string]int) bool {
    if len(x) ! =len(y) {
        return false
    }
    for k, xv := range x {
        ifyv, ok := y[k]; ! ok || yv ! = xv {return false}}return true
}
Copy the code

Use map for statistics

var m = make(map[string]int)

func k(list []string) string { return fmt.Sprintf("%q", list) }

func Add(list []string)       { m[k(list)]++ }
func Count(list []string) int { return m[k(list)] }
Copy the code

4. Structure

Structure definition

type Point struct {
 
    Salary    int
    ManagerID int
}

var p Point // Struct variables

// Another way to write it
type Point struct{ X, Y int }

p := Point{1.2}
Copy the code

As with variables and functions, constructs whose member names begin with an uppercase letter are exported. A structure may contain both exported and unexported members.

Struct as argument and return value of function:

func Scale(p Point, factor int) Point {
    return Point{p.X * factor, p.Y * factor}
}

fmt.Println(Scale(Point{1.2}, 5)) {5 10} "/ /"
Copy the code

Pointer (for efficiency), you can modify structure members in functions.

func AwardAnnualRaise(e *Employee) {
    e.Salary = e.Salary * 105 / 100
}
Copy the code

The structure is nested to simplify and clarify the definition.

/ / points
type Point struct {
    X, Y int
}
/ / round
type Circle struct {
    Center Point
    Radius int
}
/ / wheel
type Wheel struct {
    Circle Circle
    Spokes int
}
Copy the code

Access to members

var w Wheel
w.Circle.Center.X = 8
w.Circle.Center.Y = 8
w.Circle.Radius = 5
w.Spokes = 20
Copy the code

While accessing a multi-tier structure is obviously complicated, GO also provides anonymous members to handle structure nesting. The data type of an anonymous member must be a named type or a pointer to a named type.

We modify circles and wheels as follows:

type Circle struct {
    Point
    Radius int
}

type Wheel struct {
    Circle
    Spokes int
}
Copy the code

Visiting members:

var w Wheel
w.X = 8           
w.Y = 8         
w.Radius = 5     
w.Spokes = 20
Copy the code

From above, the anonymous member feature only provides short syntactic sugar for dot operators that access nested members. In go, anonymous members are not required to be struct types; Any named type can be an anonymous member of a structure. This mechanism can be used to combine objects with simple behavior into objects with complex behavior. Composition will come to the fore in go object-oriented.


Feel free to point out any shortcomings in the comments section.

Favorites, likes and questions are welcome. Follow the top water cooler managers and do something other than pipe hot water.