The fourth chapter of the Bible go language (reading notes)

Chapter IV compound data types

Array

  • Particular element array is a sequence of fixed length composed of an array may be composed of zero or more elements
  • The subject of the index ranges from 0 to the start position in the array length minus 1
  • By default, each element of the array are initialized to zero value corresponding to the type of
  • Ellipsis ... indicates the length of the array is determined based on the number of initial-value
q := [...]int{1, 2, 3}
fmt.Printf("%T\n", q) // "[3]int"
  • Length of the array is an integral part of the array type, [3] int and [4] int array is not the same type
  • Length of the array must be a constant expression
  • Between the array can be compared to each other, the comparison order of the sequence, element by element, provided that they meet: the same type, remember [3] int and [4] int is not the same type
a := [2]int{1, 2}
b := [...]int{1, 2}
c := [2]int{1, 3}
fmt.Println(a == b, a == c, b == c) // "true false false"
d := [3]int{1, 2}
fmt.Println(a == d) // compile error: cannot compare [2]int == [3]int

Slice

  • Slice (Slice) is a variable-length sequence, each element of the same type, generally written [] T
  • Slice Array functions providing access sequence (or all) of the elements, its underlying an array object references
  • Slice consists of three parts
    1 pointers: pointing to a first slice corresponding to the underlying element array element address
    2. Length: the length can not exceed the capacity, available len function obtained
    3. Volume: Volume generally range from a start position to the underlying data slice length end position, the function can be used to obtain cap
  • Slice operation can be obtained from the array slice, slice operation S [I: J]
    1. If omitted i, 0 will be used instead of
    2. If omitted, j, will be replaced by len (S)
    3. slice is obtained in a "left closing the right opening section "
    4. If exceeded cap (s) will cause panic
    5. the exceeded if len (s) but not beyond the cap (s), will be extended (referred to herein as the extension is an extension of the original slice, but directly access beyond len (s) will produce the panic element)
func main() {
  a := [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}
  s := a[:4]
  s2 := s[:7]
  fmt.Println(s, s2)//[1 2 3 4] [1 2 3 4 5 6 7]
  fmt.Println(cap(s)) //10
  fmt.Println(s[7]) //panic:index out of range
  fmt.Printf("%T\n", s)  //[]int
}
  • And String [] a similar byte slicing operation, is x [m: n], is a return to the original sequence of the sequence of bytes, the bottom layer before the underlying array are shared
  • Note that the string slicing or string, the string rather than actually slice, which is constant, but can not be used with the cap len
  s1 := "hello,world"
  s2 := s1[:5]
  fmt.Println(cap(s1))  //panic
  fmt.Println(len(s1))  //11
  fmt.Println(cap(s2))  //panic
  fmt.Println(len(s2))  //5
  fmt.Printf("%T\n", s2)  //string
  • Compared string, slice the array, you can modify data, just like a normal array as you can modify the data
  • When using a microtome modify data, you must pay attention to change the underlying data array, as a modification of the same memory space (which is actually a portion of the note Slice start explained, configuration pointer to a first slice corresponding to the bottom element array element address)
  • Of course, you can use literals to create slcie. It is the underlying array literal noted that the anonymous array
s := []int{0, 1, 2, 3, 4, 5, 6, 7, 8}
  • And the different arrays, can not be directly compared with each other between the slice
  • For [] byte comparison, there are two bytes.Equal function to determine [] byte are equal
  • Other types, you need to define your own comparison method
  • Why does not directly support comparison operations slice of it?
    1.slice is an indirect reference, may comprise its own slice
    2. a fixed slice may contain different elements at different times, because the underlying array elements may be modified
  • The only legitimate and the comparison slice is nil comparison, a slice is equal to nil value of zero, which represents no underlying array slice, both the length and capacity 0
  • There is also a non-nil value, but the capacity is the length of the slice 0, for example, [] int {} or make ([] int, 3) [3:], which is allowed
  • In practice, it must figure out what slice of empty representatives:
    1. nil?
    2. is not nil, but len = 0?
  • In both cases, len is 0, it is determined empty slice general manner may be employed len (s) == 0
  • You can use the built-in make function to create the specified slice
make([]T, len)
make([]T, len, cap) // same as make([]T, cap)[:len]

append function

  • Built-in functions to append additional elements to slice, slice or adding
var x []int
x = append(x, 1)
x = append(x, 2, 3)
x = append(x, 4, 5, 6)
x = append(x, x...) // append the slice x
fmt.Println(x)
// "[1 2 3 4 5 6 1 2 3 4 5 6]"
  • But append can not guarantee whether the memory is reallocated, can not determine a new slice and the same underlying array of whether references to the original space
  • The book gives a slice of a reference structure, to facilitate the understanding
type IntSlice struct {
    ptr
    *int
    len, cap int
}

Slice memory skills

  • This section describes examples are detailed look at the original book
  • A useful question: by the function parameter passing slice will happen then?
  • Set forth in the Examples demonstrate, for the [] string parameter passed as [] and the original parameter string [] refer to the same underlying string is a string array, but if the append process used, not necessarily the
  • Recommendation: After each treatment slice, the best overwrite the original slice
data := []string{"hello", " ", ",", "world" }
data = nonempty(data)
  • Built-in copy function, you can put back in order to move forward a slice:
copy(slice[i:], slice[i+1:])

Map

  • Map is a reference to a hash table, you can write map [K] V, that is, Key, value:
    1.key have the same type, have the same value type, key and value may be different types
    2.key of type must support the == operator, but is not recommended for use as a floating-point number key, there may be a float NaN is not equal to any floating-point number
    3. You can use the map function to get the length len
  • To create a map, recommended to use the built-in make, same here also put to the slice for comparison
var a1 []int //只是声明这么一个类型,对应的零值为nil
a2 := make([]int, 3)  //这里创建了一个[]int数据,并且长度为3,每个元素对应零值
0

var b1 map[string]int  //只是声明,对应零值为nil,不能添加值
b2 := make(map[string]int)  //这里创建了map[string]int数据,并且可以添加值了
  • From the examples cited above types of behavior are often unsatisfactory statement, we need special attention
  • map add elements is simple:
ages := make(map[string]int)
ages["alice"] = 31
ages["charlie"] = 34
  • Remove elements using the built-delete function
delete(ages, "alice") // remove element ages["alice"]
  • Query (access) elements
age1 := ages["bob"] //如果存在,返回值;否则,返回相应的零值
age2, ok := ages["bob"] //如果存在,返回value, true;否则,返回零值,false
  • Check the site to map the value is not permitted
  • The reason is that dynamic map elements of growth may lead to reallocate space, which could lead to an invalid address before
_ = &ages["bob"] // compile error: cannot take address of map element
  • Use loop through the range map, uncertain traversal order, every time a random: k, v: = range map
func equal(x, y map[string]int) bool {
    if len(x) != len(y) {
        return false
    }
    for k, xv := range x {
        if yv, ok := y[k]; !ok || yv != xv {
            return false
        }
    }
    return true
}
  • If ordering is required sorts explicit use of the package sort key values, and create an equivalent of the same type of key Slice
import "sort"
var names []string
for name := range ages {
    names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
    fmt.Printf("%s\t%d\n", name, ages[name])
}

Set type (Go does not directly provide)

  • Usually Map [T] as bool set of type T, of course, value may be other types bool meaningful values

Some of the more flexible usage

var graph = make(map[string]map[string]bool)
func addEdge(from, to string) {
    edges := graph[from]
    if edges == nil {
        edges = make(map[string]bool)
        graph[from] = edges
    }
    edges[to] = true
}
func hasEdge(from, to string) bool {
    return graph[from][to]
}

Structure

  • It is polymerized from a value of zero or more of any type of entity into
  • Members of the structure, unlike the member can not get access map (this depends on the scope, a package, deriving resistance)
  • Zero values ​​for the structure of the respective members are set to zero
  • For an empty structure struct {}, its size is 0, should be avoided

    Structure of the face value

  • Do not specify a member, will declare the order of the assignment or initialization
type Point struct{ X, Y int }
p := Point{1, 2}
  • Designated members of the assignment or initialization
p := Point{X: 1, Y: 2}
p2 := Point{
    X; 1,
    Y: 2,
}
  • Noted p2, {must Point peers, Y: 2 end need comma
  • Also note that if you are calling outside the package structure of a package, you need to export the job (start with a capital)
package p
type T struct{ a, b int } // a and b are not exported
package q
import "p"
var _ = p.T{a: 1, b: 2} // compile error: can't reference a, b
var _ = p.T{1, 2}// compile error: can't reference a, b

Comparison of structure

  • If all the members of the structure are comparable, then the structure is comparable

Embedded structures and anonymous members

  • Two examples are given below, attention is insert, as well as access form
type Point struct {
    X, Y int
}
type Circle struct {
    Center Point
    Radius int
}
type Wheel struct {
    Circle Circle
    Spokes int
}

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

Equivalents of the above code (written notes section is still valid) as follows:

type Point struct {
    X, Y int
}
type Circle struct {
    Point
    Radius int
}
type Wheel struct {
    Circle
    Spokes int
}

var w Wheel
w.X = 8 // equivalent to w.Circle.Point.X = 8
w.Y = 8 // equivalent to w.Circle.Point.Y = 8
w.Radius = 5 // equivalent to w.Circle.Radius = 5
w.Spokes = 20
  • However, the structure of the embedded member, during initialization, must be explicitly stated:
w = Wheel{Circle{Point{8, 8}, 5}, 20}
w = Wheel{
Circle: Circle{
    Point:
        Point{X: 8, Y: 8},
        Radius: 5,
    },
    Spokes: 20, // NOTE: trailing comma necessary here (and at Radius)
}
  • Embedded Anonymous members also have an implicit name, it can not contain the same type of two anonymous member
  • In fact, embedded in the members is not necessarily the structure, of any type can be named (in Chapter 6 will be devoted) as an anonymous member of the structure

JSON

  • JavaScript Object Notation (JSON) is a standard protocol and transmitting structured information is received (by the packet encoding / json support) is used, there is a similar protocol:
    1.XML (encoding / XML)
    2.ASN.1 ( encoding / ASN1)
    3.Google of Protocol Buffers (github.com/golang/protobuf)
  • JSON is a javascript values ​​in the various types of Unicode text encoding
  • JSON array indicated by square brackets, and a corresponding array of slices Go
  • JSON object is mapped to a string value, that is, a series of name: value pair comprising braces and separated by commas, may correspond to the map type Go
  • example
boolean true
number -273.15
string "She said \"Hello, BF\""
array ["gold", "silver", "bronze"]
object {"year": 1980,
        "event": "archery",
        "medals": ["gold", "silver", "bronze"]}
  • Basic Operation encoding / json of:
    1.Marshal
    2.Unmarshal
    3.MarshalIndent
    4.Decoder
    5.Encoder

  • Detailed supplementary reflective section

HTML files and templates

  • This part will not be recorded because
    1. It is generally back-end processing of data, how to present data, this would be more convenient to the front, but also reduce the pressure of the back-end data processing (but really need back-end processing, look too late)
    2. before there's a realization, are relying on the basis of language go to do, interface, reflecting not understand these, see little sense

Guess you like

Origin www.cnblogs.com/laiyuanjing/p/11227776.html