Go-Slice

2024-09-04 21:58
文章标签 go slice

本文主要是介绍Go-Slice,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

要点

  • 一个区间:[low:high]
  • 两个概念:length, capability
  • 三个函数:make(), append(), copy()

概念

Array是在声明的时候都确定了长度,之后不可更改。Slice和数组类似,也是表示一个有序元素,但这个序列的长度可变。

在Go中,Slice序列中各元素的数据类型必须一致,因为在声明slice的时候即要指定类型。

可以在Python中找到Slice,和Go的Slice基本上是一致的语义和用法。Slice中文通常被译为切片,大抵是因为可以从一个序列中存取指定的某一部分。下面是Collins词典中对于slice的解释,有助于了解该词的含义:

  • N-COUNT (指食物切下的)片,薄片 A slice of bread, meat, fruit, or other food is a thin piece that has been cut from a larger piece. 语法信息

  • VERB 将…切成薄片 If you slice bread, meat, fruit, or other food, you cut it into thin pieces.

在第一次接触Python的slice的时候,对于这个slice或切片,觉得很是怪异,因为在C/C++、Java中还没有对应的术语。——虽然substr()的功用和slice有些相似,但显然slice的用法更加简洁和灵活,更显脚本语言的本色。

以上都是废话,下面给出示例。

声明&赋值

package main
import "fmt"/*
D:\examples>go run helloworld.go
values[0]=1
values[1]=2
values[2]=3
values[3]=4
values[4]=5D:\examples>
*/
func main() {var values []int // (1)values = make([]int, 5) // (2)for i, _ := range values {values[i] = i + 1}for i, item := range values {fmt.Printf("values[%d]=%d\n", i, item)}
}

要点:

  • (1)声明:和数组类似,但是不用指定长度。在这个时候,slice的长度为0,所以还不直接放数据。
  • (2)分配存储空间:调用内置make()函数为slice分配存储空间。
  • 接下来的存取则和普通的数组语法一致。

可以看到,slice和数组非常类似的,即内部存储是有序的数组形式,访问也是索引方式,仅仅在于其动态长度特性。如此,slice又和C++ STL的vector类似,不用指定长度。vector可以声明最大capability,可以动态改变长度。此为,slice和Java的ArrayList也是类似的。所以,通俗的讲,slice也可看做列表。——Go有一个list package,后面会提到。

用Array给slice赋值

package main
import "fmt"/*
D:\examples>go run helloworld.go
the_slice[0]=3
the_slice[1]=4
the_slice[2]=5D:\examples>
*/
func main() {the_array := [5]int {1, 2, 3, 4, 5} the_slice := the_array[2:5]for i, item := range the_slice {fmt.Printf("the_slice[%d]=%d\n", i, item)}
}

要点:
- 直接用[low:high]这种方式定义一个slice
- 这里的[low:high],用数学集合的方式来讲,就是[low, high),即左闭右开。
- 这种创建slice的方式,不需要make()函数。

[low:high]

Go的[low:high]和Python的语法一致。要点:
- [:]等价于[0:len(array)]
- [:n]等价于[0:n]
- [n:]等价于[n:len(array)]

注:别挑战low小于0或high大于len(array)的这种异常。

package main
import "fmt"/*
D:\examples>go run helloworld.go
[:] elements:
the_slice[0]=1
the_slice[1]=2
the_slice[2]=3
the_slice[3]=4
the_slice[4]=5
[2:] elements:
the_slice[0]=3
the_slice[1]=4
the_slice[2]=5
[:4] elements:
the_slice[0]=1
the_slice[1]=2
the_slice[2]=3
the_slice[3]=4
[:4] elements:
the_slice[0]=1
the_slice[1]=2
the_slice[2]=3
the_slice[3]=4
[1:4] elements:
the_slice[0]=2
the_slice[1]=3
the_slice[2]=4
panic: runtime error: slice bounds out of rangegoroutine 1 [running]:
panic(0x49cba0, 0xc04200a040)C:/Go/src/runtime/panic.go:500 +0x1af
main.main()D:/examples/helloworld.go:29 +0x191
exit status 2D:\examples>
*/
func main() {the_array := [5]int {1, 2, 3, 4, 5} the_slice := the_array[:]debug_slice(the_slice, "[:] elements:")debug_slice(the_array[2:], "[2:] elements:")debug_slice(the_array[:4], "[:4] elements:")debug_slice(the_array[:4], "[:4] elements:")debug_slice(the_array[1:4], "[1:4] elements:")// invalid slice index -1 (index must be non-negative)//debug_slice(the_array[-1:40], "[-1:40] elements:")//invalid slice index 40 (out of bounds for 5-element array)//debug_slice(the_array[0:40], "[:40] elements:")//Runtime Errorthe_slice2 := make([]int, 5)debug_slice(the_slice2[0:40], "[:40] elements:")
}func debug_slice(the_slice []int, msg string) {fmt.Println(msg)for i, item := range the_slice {fmt.Printf("the_slice[%d]=%d\n", i, item)}
}

length & capability

先给出示例代码:

package main
import "fmt"/*
D:\examples>go run helloworld.go
default values of slice:
the_slice[0]=0
the_slice[1]=0
the_slice[2]=0
the_slice[3]=0
the_slice[4]=0D:\examples>
*/
func main() {var the_slice []int;the_slice = make([]int, 5, 10)debug_slice(the_slice, "default values of slice:")
}func debug_slice(the_slice []int, msg string) {fmt.Println(msg)for i, item := range the_slice {fmt.Printf("the_slice[%d]=%d\n", i, item)}
}

在make()的时候,5表示长度为5个元素,此即length的概念;10表示整个容器的长度,即capability的概念。在这里,slice可以放10个元素,但目前只放了5个元素。make()的时候会自动初始化这5个元素为缺省值(???)。

在 <> Ch4 Composite Types, P88 有如下的描述:

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

也就是说, 对于第一种情形,make直接创建长度为len的数组,并返回这个数组的元素。对于第二种情形,make会创建长度为capability的数组,但仅仅返回前面的len个元素。显然,返回的slice的长度就是len。

因为slice是依存于数组数据结构而存在,虽然第二种情形下slice的长度为len,但在添加新的元素的时候,只要不超过capability,就无须动态创建新的数组,而直接把要添加的元素放在slice已有元素的后面。

slice的length和capability的概念,和C++ STL vector对应的含义是一致的。——python的slice/list貌似没用这个概念。。。不确定。。。

当capability不至于放新的原始的时候,slice对象就会重新创建一个数组,并把原来的数据拷贝到新的数组里。

可以认为,capability对于功能无影响,但对于程序的性能会有影响。如果设置不当,会因为频繁的数据拷贝而降低性能。

TODO: 暂不清楚Go是否有OO的ctor的概念,如果有的话,用slice存放OO对象+ctor打印,会比较好的说明capability的作用。

对于以上解读,再给出一个例子:

package main
import "fmt"/*
D:\examples>go run helloworld.go
default value of slice:
the_slice[0]=0
the_slice[1]=0
the_slice[2]=0
slice:
the_slice[0]=1
the_slice[1]=2
the_slice[2]=3
the_slice[3]=4
the_slice[4]=5
the_slice[5]=6D:\examples>
*/
func main() {the_array := [6]int {1,2,3,4,5,6}the_slice := make([]int, 3, 5)debug_slice(the_slice, "default value of slice:")the_slice = the_array[:]debug_slice(the_slice, "slice:")
}func debug_slice(the_slice []int, msg string) {fmt.Println(msg)for i, item := range the_slice {fmt.Printf("the_slice[%d]=%d\n", i, item)}
}

append

append()函数是在slice后面添加元素。同前面对capability的描述,append()的时候可能涉及到数组的动态创建。

package main
import "fmt"/*
D:\examples>go run helloworld.go
slice1: 1       2       3
slice2: 1       2       3       4       5
slice1: 1       2       3       4       5       6
slice2: 1       2       3       4       5D:\examples>
*/
func main() {the_slice1 := []int {1,2,3}the_slice2 := append(the_slice1, 4, 5)debug_slice(the_slice1, "slice1:")debug_slice(the_slice2, "slice2:")the_slice1 = append(the_slice1, 4, 5, 6)debug_slice(the_slice1, "slice1:")debug_slice(the_slice2, "slice2:")//the_slice1.append undefined (type []int has no field or method append)//the_slice1.append(7)
}func debug_slice(the_slice []int, msg string) {fmt.Print(msg, "\t")for _, item := range the_slice {fmt.Print(item, "\t")}fmt.Println()
}

不清楚,为什么不支持.append()这种语法,而是append(slice, elements …)。

copy

copy()函数是把一个slice的“所有”元素拷贝到另外一个slice中。——是拷贝,而不是追加(append)。需要注意的是:如果目标slice的长度小于源slice的长度,那么就不会拷贝源slice的所有原始。

package main
import "fmt"/*
D:\examples>go run helloworld.go
slice1: 1       2       3
slice2: 0       0
slice3: 10      0       0       0
slice1: 1       2       3
slice2: 1       2
slice3: 1       2       3       0D:\examples>
*/
func main() {slice1 := []int {1,2,3}slice2 := make([]int, 2)slice3 := make([]int, 4)slice3[0] = 10debug_slice(slice1, "slice1:")debug_slice(slice2, "slice2:")debug_slice(slice3, "slice3:")copy(slice2, slice1)copy(slice3, slice1)debug_slice(slice1, "slice1:")debug_slice(slice2, "slice2:")debug_slice(slice3, "slice3:")
}func debug_slice(the_slice []int, msg string) {fmt.Print(msg, "\t")for _, item := range the_slice {fmt.Print(item, "\t")}fmt.Println()
}

附 append documentation

func append

func append(slice []Type, elems ...Type) []Type

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"...)

附 copy documentation

func copy

func copy(dst, src []Type) int

The copy built-in function copies elements from a source slice into a destination slice. (As a special case, it also will copy bytes from a string to a slice of bytes.) The source and destination may overlap. Copy returns the number of elements copied, which will be the minimum of len(src) and len(dst).

这篇关于Go-Slice的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1137147

相关文章

go中的时间处理过程

《go中的时间处理过程》:本文主要介绍go中的时间处理过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1 获取当前时间2 获取当前时间戳3 获取当前时间的字符串格式4 相互转化4.1 时间戳转时间字符串 (int64 > string)4.2 时间字符串转时间

Go语言中make和new的区别及说明

《Go语言中make和new的区别及说明》:本文主要介绍Go语言中make和new的区别及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1 概述2 new 函数2.1 功能2.2 语法2.3 初始化案例3 make 函数3.1 功能3.2 语法3.3 初始化

Go语言中nil判断的注意事项(最新推荐)

《Go语言中nil判断的注意事项(最新推荐)》本文给大家介绍Go语言中nil判断的注意事项,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1.接口变量的特殊行为2.nil的合法类型3.nil值的实用行为4.自定义类型与nil5.反射判断nil6.函数返回的

Go语言数据库编程GORM 的基本使用详解

《Go语言数据库编程GORM的基本使用详解》GORM是Go语言流行的ORM框架,封装database/sql,支持自动迁移、关联、事务等,提供CRUD、条件查询、钩子函数、日志等功能,简化数据库操作... 目录一、安装与初始化1. 安装 GORM 及数据库驱动2. 建立数据库连接二、定义模型结构体三、自动迁

Go语言代码格式化的技巧分享

《Go语言代码格式化的技巧分享》在Go语言的开发过程中,代码格式化是一个看似细微却至关重要的环节,良好的代码格式化不仅能提升代码的可读性,还能促进团队协作,减少因代码风格差异引发的问题,Go在代码格式... 目录一、Go 语言代码格式化的重要性二、Go 语言代码格式化工具:gofmt 与 go fmt(一)

Go学习记录之runtime包深入解析

《Go学习记录之runtime包深入解析》Go语言runtime包管理运行时环境,涵盖goroutine调度、内存分配、垃圾回收、类型信息等核心功能,:本文主要介绍Go学习记录之runtime包的... 目录前言:一、runtime包内容学习1、作用:① Goroutine和并发控制:② 垃圾回收:③ 栈和

Go语言中泄漏缓冲区的问题解决

《Go语言中泄漏缓冲区的问题解决》缓冲区是一种常见的数据结构,常被用于在不同的并发单元之间传递数据,然而,若缓冲区使用不当,就可能引发泄漏缓冲区问题,本文就来介绍一下问题的解决,感兴趣的可以了解一下... 目录引言泄漏缓冲区的基本概念代码示例:泄漏缓冲区的产生项目场景:Web 服务器中的请求缓冲场景描述代码

Go语言如何判断两张图片的相似度

《Go语言如何判断两张图片的相似度》这篇文章主要为大家详细介绍了Go语言如何中实现判断两张图片的相似度的两种方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 在介绍技术细节前,我们先来看看图片对比在哪些场景下可以用得到:图片去重:自动删除重复图片,为存储空间"瘦身"。想象你是一个

Go语言中Recover机制的使用

《Go语言中Recover机制的使用》Go语言的recover机制通过defer函数捕获panic,实现异常恢复与程序稳定性,具有一定的参考价值,感兴趣的可以了解一下... 目录引言Recover 的基本概念基本代码示例简单的 Recover 示例嵌套函数中的 Recover项目场景中的应用Web 服务器中

Go语言中使用JWT进行身份验证的几种方式

《Go语言中使用JWT进行身份验证的几种方式》本文主要介绍了Go语言中使用JWT进行身份验证的几种方式,包括dgrijalva/jwt-go、golang-jwt/jwt、lestrrat-go/jw... 目录简介1. github.com/dgrijalva/jwt-go安装:使用示例:解释:2. gi