首页 > 其他分享 >Golang基础-Slices

Golang基础-Slices

时间:2023-02-18 21:55:57浏览次数:50  
标签:index slice return Slices int 基础 len Golang append

声明Slice

var empty []int                 // an empty slice
withData := []int{0,1,2,3,4,5}  // a slice pre-filled with some data

make([]T, len)
make([]T, len, cap) // same as make([]T, cap)[:len]

理解cap

func appendInt(x []int, y int) []int {
	var z []int
	zlen := len(x) + 1
	if zlen <= cap(x) {
		// There is room to grow.  Extend the slice.
		z = x[:zlen]
	} else {
		// There is insufficient space.  Allocate a new array.
		// Grow by doubling, for amortized linear complexity.
		zcap := zlen
		if zcap < 2*len(x) {
			zcap = 2 * len(x)
		}
		z = make([]int, zlen, zcap)
		copy(z, x) // a built-in function; see text
	}
	z[len(x)] = y
	return z
}

append函数

a := []int{1, 3}
a = append(a, 4, 2) 
// => []int{1,3,4,2}

nextSlice := []int{100,101,102}
newSlice  := append(withData, nextSlice...)
// => []int{0,1,2,3,4,5,100,101,102}}

//slice模拟栈操作
stack = append(stack, v) // push v
top := stack[len(stack)-1] // top of stack
stack = stack[:len(stack)-1] // pop

// 删除第i位
func remove(slice []int, i int) []int {
    copy(slice[i:], slice[i+1:])
    return slice[:len(slice)-1]
}

// 删除第i位
slice = append(slice[:i], slice[i+1:]...)

三个点表示调用拥有变长参数列表的函数。我是理解成把slice拆分成单个元素,然后依次append了。

Variadic Functions

func find(a int, b ...int) {
    // ...
}

这里的三个点表示这是一个变长参数的函数。变长但参数必须在最后。变长但参数在函数内部作为一个slice,例如上述但find函数,在函数内部b是一个[]int类型的slice。

Exercise

package cards

// FavoriteCards returns a slice with the cards 2, 6 and 9 in that order.
func FavoriteCards() []int {
	return []int{2, 6, 9}
}

// GetItem retrieves an item from a slice at given position.
// If the index is out of range, we want it to return -1.
func GetItem(slice []int, index int) int {
	if index < 0 || index >= len(slice) {
		return -1
	} else {
		return slice[index]
	}
}

// SetItem writes an item to a slice at given position overwriting an existing value.
// If the index is out of range the value needs to be appended.
func SetItem(slice []int, index, value int) []int {
	if index < 0 || index >= len(slice) {
		slice = append(slice, value)
	} else {
		slice[index] = value
	}
	return slice
}

// PrependItems adds an arbitrary number of values at the front of a slice.
func PrependItems(slice []int, values ...int) []int {
	slice = append(values, slice...)
	return slice
}

// RemoveItem removes an item from a slice by modifying the existing slice.
func RemoveItem(slice []int, index int) []int {
	if index < 0 || index >= len(slice) {
		return slice
	}
	slice = append(slice[:index], slice[index+1:]...)
	return slice
}

标签:index,slice,return,Slices,int,基础,len,Golang,append
From: https://www.cnblogs.com/roadwide/p/17133737.html

相关文章