当前位置:网站首页>Section 1 array and slicing in Chapter 6
Section 1 array and slicing in Chapter 6
2022-04-23 03:27:00 【Python code doctor】
Array
summary
An array is a collection of data of the same type . Every data contained in an array is called an array element (element), The number of elements in an array is called the length of the array .
Array length must be constant , And it's part of the type . [2]int and [3]int It's different types .
var n int = 10
var a [n]int //err, non-constant array bound n
var b [10]int //ok
Operation array
Each element of the array can be accessed through index subscripts , The index range is the index range from 0 Start To the length of the array minus 1 The location of .
var a [10]int
for i := 0;i < 10; i++ {
a[i] = i + 1
fmt.Printf("a[%d] = %d\n", i, a[i])
}
// range Has two return values , The first return value is the array subscript of the element , The second return value is the value of the element
for i, v :=range a {
fmt.Println("a[", i, "]=",v)
}
Built in functions len( length ) and cap( Capacity ) Both return the length of the array ( Element quantity ):
a := [10]int{
}
fmt.Println(len(a),cap(a)) //10 10
initialization :
a := [3]int{
1, 2} // Uninitialized element value is 0
b := [...]{
1, 2, 3} // Determine the array length by initializing the value
c := [5]int{
2: 100, 4: 200} // Initializing elements with index numbers , Uninitialized element value is 0
// Support multidimensional array
d := [4][2]int{
{
10, 11}, {
20, 21}, {
40, 41}}
e := [...][2]int{
{
10, 11}, {
20, 21}, {
30, 31}, {
40, 41}} // The second dimension can't write "..."
f := [4][2]int{
1: {
20, 21}, 3: {
40, 41}}
g := [4][2]int{
1: {
0: 20}, 3: {
1: 41}}
fmt.Println(d, e, f, g)
You can use... Between arrays of the same type == or != Compare , But you can't use < or >, You can also assign values to each other :
a := [3]int{
1, 2, 3}
b := [3]int{
1, 2, 3}
c := [3]int{
1,2}
fmt.Println(a == b, b == c) //true false
var d [3]int
d = a
fmt.Println(d) //[1 2 3]
Passing arrays between functions
Based on memory and performance , Passing arrays between functions is a costly operation . When passing variables between functions , It's always delivered by value . If this variable is an array , It means the whole array , No matter how long , Will be copied completely , And pass it to the function .
func modify(array [5]int) {
array[0] = 10 // The view modifies the first element of the array
// In modify(), array values: [10 2 3 4 5]
fmt.Println("In modify(), array values:", array)
}
func main() {
array := [5]int{
1, 2, 3 ,4, 5} // Define and initialize an array
modify(array) // Pass it to a function , And try to modify the contents of the array in the function
//In main(), array values: [1 2 3 4 5]
fmt.Println("In main(), array values:", array)
}
Array pointer as function parameter :
func modify(array *[5]int) {
(*array)[0] = 10
// In modify(), array values: [10 2 3 4 5]
fmt.Println("In modify(),array values:", *array)
}
func main() {
array := [5]int{
1, 2, 3, 4, 5} // Define and initialize an array
modify(&array)
// In main(), array values: [10 2 3 4 5]
fmt.Println("In main(), array values:", array)
}
section
summary
The length of the array cannot be modified after it is defined ; Arrays are value types , Each delivery will produce a copy . Obviously, this kind of data structure can not fully meet the real needs of developers .Go The language provides array slicing (slice) To make up for the array .
Slices are not arrays or array pointers , It refers to... Through internal pointers and related properties ⽤ Array ⽚ paragraph , To achieve change ⻓⽅ case .
slice It's not really a dynamic array , It's a reference type .slice Always point to the bottom array,slice The statement can also look like array equally , It just doesn't need length .

Creation and initialization of slices
slice The difference with arrays : When you declare an array , Square brackets indicate the length or use of the array … Calculate the length automatically , The statement slice when , There are no characters in brackets .
var s1 []int // Declaration slices and declarations array equally , Knowledge is short of length , This is empty (nil) section
s2 := []int{
}
// make([]T, length, capacity) //capacity Omit , And length The value of is the same
var s3 [int] = make([]int, 0)
s4 :=make([]int, 0, 0)
s5 := []int{
1, 2, 3} // Create slices and initialize
Be careful :make Can only be created slice、map and channel, And return an initial value ( Nonzero ).
Operation of slicing
Slice off
| operation | meaning |
|---|---|
| s[n] | section s The index position is n The item |
| s[:] | From slice s Index position of 0 To len(s)-1 Slices obtained at |
| s[low:] | From slice s Index position of low To len(s)-1 Slices obtained at |
| s[:high] | From slice s Index position of 0 To high Slices obtained at ,len=high |
| s[low:high] | From slice s Index position of low To high Slices obtained at ,len=high-low,cap=max-low |
| s[low:high:max] | From slice s Index position of low To high Slices obtained at ,len=high-low,cap=max-low |
| len(s) | section s The length of , Always <=cap(s) |
| cap(s) | section s The capacity of , Always >=len(s) |
example :
array := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
| operation | result | len | cap | explain |
|---|---|---|---|---|
| array[:6:8] | [0 1 2 3 4 5] | 6 | 8 | Omit low |
| array[5:] | [5 6 7 8 9] | 5 | 5 | Omit high、max |
| array[:3] | [0 1 2] | 3 | 10 | Omit high、max |
| array[:] | [0 1 2 3 4 5 6 7 8 9] | 10 | 10 | Omit all |
Slice and underlying array relationships
s := []int{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
s1 := s[2:5] //[2 3 4]
s1[2] = 100 // Modify the slice to change the underlying array
fmt.Println(s1, s) //[2 3 100] [0 1 2 3 100 5 6 7 8 9]
s2 := s1[2:6] // The new slice still points to the original underlying array [100 5 6 7]
s2[3] = 200
fmt.Println(s2) //[100 5 6 200]
fmt.Println(s) //[0 1 2 3 100 5 6 200 8 9]
Built-in functions
append
append Functional direction slice Add data at the end , Return to new slice object :
var s1 []int // establish nil Switch
//s1 := make([]int, 0)
s1 = append(s1, 1) // Additional 1 Elements
s1 = append(s1, 2, 3) // Additional 2 Elements
s1 = append(s1, 4, 5, 6) // Additional 3 Elements
fmt.Println(s1) //[1 2 3 4 5 6]
s2 := make([]int, 5)
s2 = append(s2, 6)
fmt.Println(s2) //[0 0 0 0 0 6]
s3 := []int{
1, 2, 3}
s3 = append(s3, 4, 5)
fmt.Println(s3)//[1 2 3 4 5]
append The function intelligently increases the capacity of the underlying array , Once the capacity of the original underlying array is exceeded , Usually, the 2 Double the capacity to reallocate the underlying array , And copy the original data :
func main() {
s := make([]int, 0, 1)
c := cap(s)
for i := 0; i < 50; i++ {
s = append(s, i)
if n := cap(s); n > c {
fmt.Printf("cap: %d -> %d\n", c, n)
c = n
}
}
/* cap: 1 -> 2 cap: 2 -> 4 cap: 4 -> 8 cap: 8 -> 16 cap: 16 -> 32 cap: 32 -> 64 */
}
copy
function copy In two slice Copy data between , Copy ⻓ Du Yi len Small is the standard. , Two slice Can point to the same ⼀ The underlying array .
data := [...]int{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
s1 := data[8:] //{8, 9}
s2 := data[:5] //{0, 1, 2, 3, 4}
copy(s2, s1) // dst:s2, src:s1
fmt.Println(s2) //[8 9 2 3 4]
fmt.Println(data) //[8 9 2 3 4 5 6 7 8 9]
Slice as a function parameter
func test(s []int) {
// Slice as a function parameter
s[0] = -1
fmt.Println("test : ")
for i, v := range s {
fmt.Printf("s[%d]=%d, ", i, v)
//s[0]=-1, s[1]=1, s[2]=2, s[3]=3, s[4]=4, s[5]=5, s[6]=6, s[7]=7, s[8]=8, s[9]=9,
}
fmt.Println("\n")
}
func main() {
slice := []int{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
test(slice)
fmt.Println("main : ")
for i, v := range slice {
fmt.Printf("slice[%d]=%d, ", i, v)
//slice[0]=-1, slice[1]=1, slice[2]=2, slice[3]=3, slice[4]=4, slice[5]=5, slice[6]=6, slice[7]=7, slice[8]=8, slice[9]=9,
}
fmt.Println("\n")
}
版权声明
本文为[Python code doctor]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220619244299.html
边栏推荐
- Oracle query foreign keys contain comma separated data
- Node configuration environment CMD does not take effect
- Punch in: 4.23 C language chapter - (1) first knowledge of C language - (12) structure
- 批量下载文件----压缩后再下载
- QT uses drag and drop picture to control and mouse to move picture
- Seminar playback video: how to improve Jenkins' ability to become a real Devops platform
- Detailed explanation of socket programming send() and recv() functions
- Flink实时数仓项目—DWS层设计与实现
- Problem B: small challenge
- JS calculates the display date according to the time
猜你喜欢

研讨会回放视频:如何提升Jenkins能力,使其成为真正的DevOps平台

2022 团体程序设计天梯赛 模拟赛 L2-3 浪漫侧影 (25 分)

MySQL query specifies that a row is sorted to the first row

Configure automatic implementation of curd projects

How to achieve centralized management, flexible and efficient CI / CD online seminar highlights sharing

Chapter 9 of C language programming (fifth edition of Tan Haoqiang) analysis and answer of exercises for users to establish their own data types

2022 团体程序设计天梯赛 模拟赛 L2-1 盲盒包装流水线 (25 分)

软件测试相关知识~

超好用的Excel异步导出功能

New ORM framework -- Introduction to beetlsql
随机推荐
C set
WinForm allows the form form to switch between the front and active states
js 中,为一个里面带有input 的label 绑定事件后在父元素绑定单机事件,事件执行两次,求解
socket编程 send()与 recv()函数详解
MySQL之explain关键字详解
Learn about I / O flow and file operations
关于idea调试模式下启动特别慢的优化
浅学一下I/O流和File类文件操作
Idempotency practice operation, explaining idempotency based on business
C abstract class
JS implementation of new
MySQL installation pit
General test technology [II] test method
Unity knowledge points (ugui)
Batch download of files ---- compressed and then downloaded
Super easy to use [general excel import function]
2021-08-31
Build websocket server in. Net5 webapi
批量下載文件----壓縮後再下載
Optimization of especially slow startup in idea debugging mode