Go language learning Notes-data

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Array

Arrays are very different from previous perceptions.

    • Arrays are value types, assignments, and delegates replicate the entire array instead of pointers.
    • The length of the array must be constant and be part of the type. [2]int and [3]int are different types.
    • the "= =", "! =" operators are supported because memory is always initialized.
    • pointer array [n]T, array pointer [n]t
      can be initialized with compound statements. Supports multidimensional arrays
      a := [3]int{1, 2}// 未初始化元素值为 0。b := [...]int{1, 2, 3, 4} // 通过初始化值确定数组⻓长度。c := [5]int{2: 100, 4:200} // 使用用索引号初始化元素。d := [...]struct {  name string  age  uint8}{  {"user1", 10}, // 可省略元素类型。  {"user2", 20}, // 别忘了最后一一行行的逗号。}  a := [2][3]int{{1, 2, 3}, {4, 5, 6}}b := [...][2]int{{1, 1}, {2, 2}, {3, 3}}// 第 2 纬度不能用用 "..."。

      The value copy behavior can cause performance problems, and it is generally recommended to use slice, or array pointers.

Slice

It is necessary to note that slice is not an array or array pointer. It references array fragments through internal pointers and related properties to achieve a variable-length scheme.
Runtime.h

struct Slice{// must not move anything    byte* array; // actual data    uintgo len; // number of elements    uintgo cap; // allocated number of elements};
    • The reference type. But itself is a struct, the value copy passes.
    • The property Len represents the number of available elements, and read and write operations cannot exceed the limit.
    • The attribute cap represents the maximum expansion capacity and cannot exceed the array limit.
    • if slice = = Nill, then the Len and cap results are 0.
data := [...]int{0, 1, 2, 3, 4, 5, 6}slice := data[1:4:5]  //[low : heigh : max]

Slice


The slice object can be created directly, and the underlying array is automatically assigned.

s1 := []int{0, 1, 2, 3, 8: 100}// 通过初始化表达式构造,可使用用索引号。fmt.Println(s1, len(s1), cap(s1))s2 := make([]int, 6, 8)// 使用用 make 创建,指定 len 和 cap 值。fmt.Println(s2, len(s2), cap(s2))s3 := make([]int, 6)// 省略 cap,相当于 cap = len。fmt.Println(s3, len(s3), cap(s3))//输出:[0 1 2 3 0 0 0 0 100] 9 9[0 0 0 0 0 0] 6 8[0 0 0 0 0 0] 6 6

Using make to dynamically create slice avoids the hassle of arrays having to use constants for length. You can also use pointers to directly access the underlying array and degenerate into normal array operations.

Append operation

Adds data to the slice tail to return the new slice object.

s := make([]int, 0, 5)fmt.Printf("%p\n", &s)s2 := append(s, 1)fmt.Printf("%p\n", &s2)fmt.Println(s, s2)//输出:0x2102300000x210230040[] [1]

Copy

The function copy copies data between two slice, and the copy length is the size of Len. Two slice can point to the same underlying array, allowing the element interval to overlap. You should copy the required data to a smaller slice in time to release the extra-large underlying array memory.

Map

Reference type, hash table. The key must be a type that supports the equality operator (= =,! =), such as number, string, pointer, array, struct, and the corresponding interface. The value can be any type and there is no limit.

m := map[int]struct {    name string    age int}{    1: {"user01",10}    2: {"user02",20}}println(m[1].name)

Giving the Make function a reasonable number of parameters in advance can help improve performance. Because a large chunk of memory is requested beforehand, it is possible to avoid frequent expansion in subsequent operations.

m := make(map[string]int, 1024)

Map Common operations:

m := map[string]int{    "a": 1,}if v, ok := m["a"]; ok {// 判断 key 是否存在。    println(v)}println(m["c"]) // 对于不存在的 key,直接返回 \0,不会出错。m["b"] = 2 // 新增或修改。delete(m, "c") // 删除。如果 key 不存在,不会出错。println(len(m)) // 获取键值对数量。cap 无无效。for k, v := range m { // 迭代,可仅返回 key。随机顺序返回,每次都不相同。    println(k, v)}

Struct

Value types, assignments, and delegates copy all content. You can define a fill field by using "_", which supports pointer members to their own type. Sequential initialization must contain all fields, otherwise an error occurs. Supports anonymous structures, which can be used as struct members or as defined variables. the "= =", "! =" equality operators are supported and can be used as the map key type. A field label can be defined and read with reflection. Tags are part of a type.

type File struct {    name string    size int     attr struct {        perm int        owner int    }}f := File{    name: "test.txt",    size: 1025,    // attr: {0755, 1},// Error: missing type in composite literal}f.attr.owner = 1f.attr.perm = 0755var attr = struct {    perm  int    owner int}{2, 0755}f.attr = attr

An empty structure "saves" memory, such as a "static class" used to implement a set data structure, or to implement a method without a "state".

var null struct{}set := make(map[string]struct{})set["a"] = null

Anonymous fields

The anonymous field is simply a syntactic sugar, essentially a field with the same name as the member type (without the package name). The anonymous embedding can be any type, and of course the pointer is included.

type User struct {    name string}type Manager struct {    User    title string}m := Manager {    User:User{"Tonny"},  //匿名字段的显式字段名,和类型名相同。    title:"Administrator",}

Anonymous field members can be accessed in the same way as normal fields, and the compiler looks for all levels of anonymous fields from the outside, until a target is found or an error occurs. The outer-Name field obscures the embedded field members, and the same-level fields with the same names can make the compiler disoriented. The workaround is to use an explicit field name. You cannot embed one type and its pointer type at the same time, because they have the same name.

Object oriented

In the three main features of object-oriented, Go only supports encapsulation, although the memory layout and behavior of anonymous fields are similar to inheritance. There is no class keyword, no inheritance, polymorphism, and so on.

type User struct {    id    int    name string}type Manager struct {    User    title string}m := Manager{User{1, "Tom"}, "Administrator"}// var u User = m  // Error: cannot use m (type Manager) as type User in assignment                  // 没有继承,自自然也不会有多态。var u User = m.User// 同类型拷⻉贝。

The memory layout is the same as the C struct, without any additional object information.


Memony Info
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.