MDGSF Software Engineer

[GO] slice

2018-01-16
GO

Example 1

package main

import "fmt"

func main() {
    scores := make([]int, 0, 5)
    c := cap(scores)
    fmt.Println(c)
    for i := 0; i < 25; i++ {
        scores = append(scores, i)
        if cap(scores) != c {
            c = cap(scores)
            fmt.Println(c)
        }
    }
}
$ go run test.go
5
10
20
40

Example 2

package main

import "fmt"

func main() {
    scores := make([]int, 5)
    fmt.Println(scores, len(scores), cap(scores))

    scores = append(scores, 9332)
    fmt.Println(scores, len(scores), cap(scores))
}
$ go run test.go
[0 0 0 0 0] 5 5
[0 0 0 0 0 9332] 6 10

Example 3 删除切片元素

package main

import "fmt"

func main() {
    scores := []int{1, 2, 3, 4, 5}
    scores = removeAtIndex(scores, 2)
    fmt.Println(scores)
}

func removeAtIndex(source []int, index int) []int {
    lastIndex := len(source) - 1
    source[index], source[lastIndex] = source[lastIndex], source[index]
    return source[:lastIndex]
}
$ go run test.go
[1 2 5 4]

Example 4 copy切片元素

package main

import (
    "fmt"
    "math/rand"
    "sort"
)

func main() {
    scores := make([]int, 100)
    for i := 0; i < 100; i++ {
        scores[i] = int(rand.Int31n(2000))
    }
    sort.Ints(scores)
    fmt.Println(scores)

    worst1 := make([]int, 5)
    copy(worst1, scores[:5])
    fmt.Println(worst1)

    worst2 := make([]int, 5)
    copy(worst2[2:4], scores[:5])
    fmt.Println(worst2)

    worst3 := make([]int, 5)
    copy(worst3, scores[:10])
    fmt.Println(worst3)

    // panic: runtime error: slice bounds out of range
    // worst4 := make([]int, 5)
    // copy(worst4[:10], scores[:10])
    // fmt.Println(worst4)
}
$ go run copyDemo.go
[2 47 59 59 78 81 81 147 156 159 162 199 205 258 266 287 324 376 408 413 420 425 433 451 456 495 503 510 511 538 540 546 552 563 605 623 631 643 694 705 728 783 790 831 878 888 888 953 1000 1002 1015 1026 1033 1089 1090 1094 1106 1107 1133 1137 1189 1194 1202 1211 1237 1241 1274 1300 1318 1336 1353 1355 1356 1387 1429 1445 1447 1463 1466 1485 1528 1541 1561 1563 1577 1598 1703 1718 1721 1737 1746 1828 1843 1847 1887 1891 1940 1947 1957 1996]
[2 47 59 59 78]
[0 0 2 47 0]
[2 47 59 59 78]

weixingongzhonghao

上一篇 [GO] select

下一篇 [GO] Worker线程

Comments

Content