码迷,mamicode.com
首页 > 其他好文 > 详细

A Tour of Go Making slices

时间:2014-10-27 01:44:02      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   sp   div   on   log   

Slices are created with the make function. It works by allocating a zeroed array and returning a slice that refers to that array:

a := make([]int, 5)  // len(a)=5

To specify a capacity, pass a third argument to make:

b := make([]int, 0, 5) // len(b)=0, cap(b)=5

b = b[:cap(b)] // len(b)=5, cap(b)=5
b = b[1:]      // len(b)=4, cap(b)=4

package main 

import "fmt"

func main() {
    a := make([]int, 5)
    printSlice("a", a)
    b := make([]int, 0, 5)
    printSlice("b", b)
    c := b[:2]
    printSlice("c", c)
    d := c[2:5]
    printSlice("d", d)
}

func printSlice(s string, x []int) {
    fmt.Printf("%s len=%d cap=%d %v\n",
        s, len(x), cap(x), x)
}

 

A Tour of Go Making slices

标签:style   blog   color   io   ar   sp   div   on   log   

原文地址:http://www.cnblogs.com/ghgyj/p/4053320.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!