Go-append使用方法及注意事项

语法

原型

在go/src/builtin/builtin.go中对append说明如下:

// The append built-in function appends elements to the end of a slice. If
// it has sufficient capacity, the destination is resliced to accommodate the
// new elements. If it does not, a new underlying array will be allocated.
// Append returns the updated slice. It is therefore necessary to store the
// result of append, often in the variable holding the slice itself:
//  slice = append(slice, elem1, elem2)
//  slice = append(slice, anotherSlice...)
// As a special case, it is legal to append a string to a byte slice, like this:
//  slice = append([]byte("hello "), "world"...)
func append(slice []Type, elems ...Type) []Type

要点

  • 用append把一个或多个元素添加在一个slice的后面;
  • append的slice有一个underlying array,此即slice和array的关系;
  • 另外slice有一个length和capability的概念;
  • 如果slice还有剩余的空间,可以添加这些新元素,那么append就将新的元素放在slice后面的空余空间中;
  • 如果slice的空间不足以放下新增的元素,那么就需要重现创建一个数组;这时可能是alloc、也可能是realloc的方式分配这个新的数组;
  • 也就是说,这个新的slice可能和之前的slice在同一个起始地址上,也可能不是一个新的地址。——通常而言,是一个新的地址。
  • 分配了新的地址之后,再把原来slice中的元素逐个拷贝到新的slice中,并返回。

类比

这个slice可以和C++的vector作类比。为此,可以参考《C++源码剖析》4.2.5 vector的构造与内存管理。

示例

代码

package main

import (
    "fmt"
)

type Employee struct {
    name string
    city string
}

func (e *Employee)String() string {
    return fmt.Sprintf("Employee[address: %p, name: %s, city: %s]", e, e.name, e.city)
}

var g_employees = []Employee{}
//var g_employees = make([]Employee, 0, 4)

func add(employee *Employee) {
    g_employees = append(g_employees, *employee)
}

func debug() {
    count := len(g_employees)
    for i := 0; i < count; i++ {
        fmt.Printf("%d: %s\n", i, &(g_employees[i]))
    }
    fmt.Println()
}

func main() {
    one := Employee{name: "name1", city:"city1"}
    two := Employee{name: "name2", city:"city2"}
    three := Employee{name: "name3", city:"city3"}
    four := Employee{name: "name4", city:"city4"}

    add(&one)
    debug()

    add(&two)
    debug()

    add(&three)
    debug()

    add(&four)
    debug()
}

运行结果

Case 1: var g_employees = []Employee{}

0: Employee[address: 0xc42000e100, name: name1, city: city1]

0: Employee[address: 0xc4200101c0, name: name1, city: city1]
1: Employee[address: 0xc4200101e0, name: name2, city: city2]

0: Employee[address: 0xc420086000, name: name1, city: city1]
1: Employee[address: 0xc420086020, name: name2, city: city2]
2: Employee[address: 0xc420086040, name: name3, city: city3]

0: Employee[address: 0xc420086000, name: name1, city: city1]
1: Employee[address: 0xc420086020, name: name2, city: city2]
2: Employee[address: 0xc420086040, name: name3, city: city3]
3: Employee[address: 0xc420086060, name: name4, city: city4]

Case 2: var g_employees = make([]Employee, 0, 4)

0: Employee[address: 0xc420074000, name: name1, city: city1]

0: Employee[address: 0xc420074000, name: name1, city: city1]
1: Employee[address: 0xc420074020, name: name2, city: city2]

0: Employee[address: 0xc420074000, name: name1, city: city1]
1: Employee[address: 0xc420074020, name: name2, city: city2]
2: Employee[address: 0xc420074040, name: name3, city: city3]

0: Employee[address: 0xc420074000, name: name1, city: city1]
1: Employee[address: 0xc420074020, name: name2, city: city2]
2: Employee[address: 0xc420074040, name: name3, city: city3]
3: Employee[address: 0xc420074060, name: name4, city: city4]

分析

在调试打印中,特别把对象的地址打印处理。通过输出,可以有如下结论:

  • 在一个capability为0的空slice上面增加一个元素的时候,加1个、2个、3个的时候会重新分配存储空间;
  • 同时伴随对象拷贝。

变化的对象与不变的指针

如果slice中存放的是对象,那么在用指针处理这些对象的时候就要特别注意。比如现在全局变量采用第一种方式:

var g_employees = []Employee{}

main()代码改为:

func main() {
    one := Employee{name: "name1", city:"city1"}
    two := Employee{name: "name2", city:"city2"}
    three := Employee{name: "name3", city:"city3"}
    four := Employee{name: "name4", city:"city4"}

    add(&one)
    debug()

    var p *Employee
    p = &(g_employees[0])
    fmt.Printf("p: %s\n\n", p)

    add(&two)
    debug()
    fmt.Printf("p: %s\n\n", p)

    add(&three)
    debug()
    fmt.Printf("p: %s\n\n", p)

    add(&four)
    debug()
    fmt.Printf("p: %s\n\n", p)
}

在增加了一个元素之后,就定义一个指针指向该元素。运行结果:

0: Employee[address: 0xc420074000, name: name1, city: city1]

p: Employee[address: 0xc420074000, name: name1, city: city1]

0: Employee[address: 0xc420076140, name: name1, city: city1]
1: Employee[address: 0xc420076160, name: name2, city: city2]

p: Employee[address: 0xc420074000, name: name1, city: city1]

0: Employee[address: 0xc420082000, name: name1, city: city1]
1: Employee[address: 0xc420082020, name: name2, city: city2]
2: Employee[address: 0xc420082040, name: name3, city: city3]

p: Employee[address: 0xc420074000, name: name1, city: city1]

0: Employee[address: 0xc420082000, name: name1, city: city1]
1: Employee[address: 0xc420082020, name: name2, city: city2]
2: Employee[address: 0xc420082040, name: name3, city: city3]
3: Employee[address: 0xc420082060, name: name4, city: city4]

p: Employee[address: 0xc420074000, name: name1, city: city1]

可以看到指针指向的地址虽然一直不变,但已经不是我们所预期的对象了。

变通

现在让slice中存储对象地址,而不再是对象。

示例一

package main

import (
    "fmt"
)

type Employee struct {
    name string
    city string
}

func (e *Employee)String() string {
    return fmt.Sprintf("Employee[address: %p, name: %s, city: %s]", e, e.name, e.city)
}

var g_employees = []*Employee{}

func add(employee *Employee) {
    g_employees = append(g_employees, employee)
}

func debug() {
    count := len(g_employees)
    for i := 0; i < count; i++ {
        fmt.Printf("%d: %s\n", i, g_employees[i])
    }
    fmt.Println()
}

func main() {
    one := Employee{name: "name1", city:"city1"}
    two := Employee{name: "name2", city:"city2"}
    three := Employee{name: "name3", city:"city3"}
    four := Employee{name: "name4", city:"city4"}

    add(&one)
    debug()

    var p *Employee
    p = g_employees[0]
    fmt.Printf("p: %s\n\n", p)

    add(&two)
    debug()
    fmt.Printf("p: %s\n\n", p)

    add(&three)
    debug()
    fmt.Printf("p: %s\n\n", p)

    add(&four)
    debug()
    fmt.Printf("p: %s\n\n", p)
}

运行结果:

0: Employee[address: 0xc42000e1a0, name: name1, city: city1]

p: Employee[address: 0xc42000e1a0, name: name1, city: city1]

0: Employee[address: 0xc42000e1a0, name: name1, city: city1]
1: Employee[address: 0xc42000e1c0, name: name2, city: city2]

p: Employee[address: 0xc42000e1a0, name: name1, city: city1]

0: Employee[address: 0xc42000e1a0, name: name1, city: city1]
1: Employee[address: 0xc42000e1c0, name: name2, city: city2]
2: Employee[address: 0xc42000e1e0, name: name3, city: city3]

p: Employee[address: 0xc42000e1a0, name: name1, city: city1]

0: Employee[address: 0xc42000e1a0, name: name1, city: city1]
1: Employee[address: 0xc42000e1c0, name: name2, city: city2]
2: Employee[address: 0xc42000e1e0, name: name3, city: city3]
3: Employee[address: 0xc42000e200, name: name4, city: city4]

p: Employee[address: 0xc42000e1a0, name: name1, city: city1]

示例二

package main

import (
    "fmt"
)

type Employee struct {
    name string
    city string
}

func (e *Employee)String() string {
    return fmt.Sprintf("Employee[address: %p, name: %s, city: %s]", e, e.name, e.city)
}

var g_employees = []*Employee{}

func add(index int) {
    g_employees = append(g_employees,
        &Employee{
            fmt.Sprintf("name%d", index),
            fmt.Sprintf("city%d", index)})
}

func debug() {
    count := len(g_employees)
    for i := 0; i < count; i++ {
        fmt.Printf("%d: %s\n", i, g_employees[i])
    }
    fmt.Println()
}

func main() {
    add(1)
    debug()

    var p *Employee
    p = g_employees[0]
    fmt.Printf("p: %s\n\n", p)

    add(2)
    debug()
    fmt.Printf("p: %s\n\n", p)

    add(3)
    debug()
    fmt.Printf("p: %s\n\n", p)

    add(4)
    debug()
    fmt.Printf("p: %s\n\n", p)
}

运行结果不变。

阅读更多

没有更多推荐了,返回首页