Go中的Array和Slice

栏目: Go · 发布时间: 7年前

内容简介:翻译来于:在下面的使用会出现错误:扩展版本的extend

Go中的Array和Slice

翻译来于: https://blog.golang.org/slices

操作

extend

func Extend(slice []int, element int) []int {
    n := len(slice)
    slice = slice[0 : n+1]
    slice[n] = element
    return slice
}

在下面的使用会出现错误:

func main() {
    var iBuffer [10]int
    slice := iBuffer[0:0]
    for i := 0; i < 20; i++ {
        slice = Extend(slice, i)
        fmt.Println(slice)
    }
}
底层的buffer最大长度为10,所有在extend到10的时候会出现out of range

扩展版本的extend

func Extend(slice []int, element int) []int {
    n := len(slice)
    if n == cap(slice) {
        // Slice is full; must grow.
        // We double its size and add 1, so if the size is zero we still grow.
        newSlice := make([]int, len(slice), 2*len(slice)+1)
        copy(newSlice, slice)
        slice = newSlice
    }
    slice = slice[0 : n+1]
    slice[n] = element
    return slice
}

首先要保证len和cap的带下关系。当len不等于cap的时候extends slice 的大小。

copy

copy(newSlice, slice)
copy(slice[index+1:], slice[index:])

一定要保证容量的问题

array to slice

var array = [n]int

slice = array[:]

slice = array[begin:end]

slice to array

在调用append方法的时候需要传入的是个数不定的element

func Append(slice []int, elements ...int) []int{

}

slice1 := []int{0, 1, 2, 3, 4}
slice2 := []int{55, 66, 77}
slice1 = Append(slice1, slice2...) // The '...' is essential!

nil slice 和 empty slice

参考: https://blog.golang.org/go-slices-usage-and-internals

var slice []int
这里的slice==nil
但是

slice = make([]int,0,0)
slice不等于nil

cap len 操作

nil slice的cap和len的大小都为0
并且可以使用append操作

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Out of Control

Out of Control

Kevin Kelly / Basic Books / 1995-4-14 / USD 22.95

Out of Control is a summary of what we know about self-sustaining systems, both living ones such as a tropical wetland, or an artificial one, such as a computer simulation of our planet. The last chap......一起来看看 《Out of Control》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具