当前位置:网站首页>Go basic notes_ 5_ Array slice
Go basic notes_ 5_ Array slice
2022-07-24 02:21:00 【xcSpark】
One . Array
1. Introduce
An array is a sequence of numbered, fixed length data items of the same unique type , This type can be any primitive type such as shaping 、 String or custom type . More use slices
An array is a numbered sequence of elements of a single type , Called element type .
The number of elements is called the length of the array , And it will never be negative .
Arrays are useful for planning the detailed layout of memory .
- An array is a value . Assigning one array to another will copy all elements .
- Especially if you pass an array to a function , It will receive a copy of the array , Not a pointer to it .
- The size of an array is part of its type . type [10]int and [20]int Is different .
- Different arrays always represent different storage .
2. Using an array
Array elements can be indexed ( Location ) To read ( Or modify ), Index from 0 Start , The first element index is 0, The second index is 1, And so on . The subscript value range of the array is from 0 Start , Until the length decreases 1.
// Declare and initialize arrays
var name [SIZE]type
// Array assignment
name[index] = value
Array access
package main
import "fmt"
func main() {
// Definition 5 Array of integers
var arr [5]int
fmt.Println(" First element arr[0]=", arr[0], "\n The last element arr[len(arr)-1]=", arr[len(arr)-1])
// Print indexes and elements
for i, v := range arr {
fmt.Printf(" Indexes :%d Elements :%d\n", i, v)
}
}
# Print the results
First element arr[0]= 0
The last element arr[len(arr)-1]= 0
Indexes :0 Elements :0
Indexes :1 Elements :0
Indexes :2 Elements :0
Indexes :3 Elements :0
Indexes :4 Elements :0
Array comparison
// ... Indicates that the length of the array depends on the initial number
arr2 := [...]int{
1, 2, 3, 4, 5}
fmt.Printf("%T\n", arr2)
arr3 := [...]int{
1, 2, 3, 4, 6}
// arr2 and arr3 Only when the number and type of elements are the same can we compare
if arr2 == arr3 {
fmt.Println("arr2 == arr3")
} else {
fmt.Println("arr2 != arr3")
}
// The result is
[5]int
arr2 != arr3
Array assignment
var arr4 [2]string
// assignment
arr4[0] = "a"
fmt.Println(" First element :", arr4[0])
fmt.Println(" The second element :", arr4[1])
First element : a
The second element :
3. Multidimensional arrays
var name [size1]...[sizen]type
// Two dimensional array
var arr5 [3][2]int
fmt.Println("arr5[0][1]:", arr5[0][1])
// Declare initializing the first element , Indexes 2 The elements of , The index at this time is 1 Default for 0
arr5 = [3][2]int{
0: {
1, 2}, 2: {
6, 7}}
fmt.Println("arr5[0][1]:", arr5[0][1])
fmt.Println("arr5[1][0]:", arr5[1][0])
fmt.Println("arr5[2][1]:", arr5[2][0])
fmt.Println("arr5[2][1]:", arr5[2][1])
// Running results
arr5[0][1]: 0
arr5[0][1]: 2
arr5[1][0]: 0
arr5[2][0]: 6
arr5[2][1]: 7
Two . section
1. Introduce
Slices are descriptors of successive segments of the underlying array , And provide access to the number sequence of the elements in the array . Slice package array , More general for data series 、 More powerful 、 More convenient interface . The length of the array is immutable , Slicing can add elements .
Be careful :Go Most array programming in is done using slices rather than simple arrays . The slice itself is passed by value
section Contains references to the underlying array , If you assign one slice to another , Then both reference the same array .
If the function accepts slice parameters , Then its changes to the slice element will be visible to the caller , Similar to passing a pointer to the underlying array .
- The element types are the same
- A slice type represents a collection of all array slices of its element type .
- The number of elements is called the length of the slice , And it will never be negative .
- The value of uninitialized slice is nil.
2. Slice using
Declaration slice
The difference from the declaration of an array is , Slice declaration has no number of elements
// Declare a new slice name Slice name ,T Element type
var name []T
// Generate slices from contiguous memory areas
slice [startIndex : endIndex]
Generate slices from an array
package main
import "fmt"
func main() {
var arr = [5]int{
1, 2, 3, 4, 5}
// Generate slices from an array
fmt.Println(" section arr[0:2]:", arr[0:2])
// When the subscript is the last subscript of the array , The last element of the array cannot be extracted
fmt.Println(" section arr[0:4]:", arr[0:4])
// startIndex by 0,endIndex Default time , Take out all the elements of the array
fmt.Println("arr[0:]:", arr[0:])
// Slice reset , Empty elements
fmt.Println("arr[0:0]:", arr[0:0])
}
// result
section arr[0:2]: [1 2]
section arr[0:4]: [1 2 3 4]
arr[0:]: [1 2 3 4 5]
arr[0:0]: []
Slices are dynamic structures , Only with nil Determine equality , Can't judge each other equal . After declaring a new slice , have access to append() Function to add elements to the slice .
// Declare string type slice
var strSlice []string
// Declaration initialization int Type slice
var intSlice = []int{
1, 2}
fmt.Println("strSlice == nil ", strSlice == nil)
fmt.Println("intSlice == nil ", intSlice == nil)
fmt.Println("len(intSlice) ", len(intSlice))
// append Additive elements
strSlice = append(strSlice, "add_1")
fmt.Println("strSlice ", strSlice)
// result
strSlice == nil true
intSlice == nil false
len(intSlice) 2
strSlice [add_1]
3. make Structural slice
Created slices make Always allocate a new hidden array , The returned slice value refers to the array .
make A memory allocation operation has occurred .
// T Element type ,length The number of elements allocated by this type ,capacity Number of preallocated elements
make( []T, length, capacity)
// make Structural slice
a := make([]int, 3)
b := make([]int, 3, 6)
fmt.Println("a:", a, "b:", b)
fmt.Println("len(a) ", len(a), "len(b) ", len(b))
// result
a: [0 0 0] b: [0 0 0]
len(a) 3 len(b) 3
// Generate the same slice as allocating an array and slicing it , The following two expressions are equivalent
make([]int, 50, 100)
new([100]int)[0:50]
Be careful :
It's like an array , Slices are always one-dimensional , But it can be combined to construct higher dimensional objects .
For arrays of arrays , Internal arrays are always of the same length in construction .
But for slice slice ( Or slice array ), The internal length may change dynamically .
Besides , Internal slices must be initialized separately .
4. Two dimensional slices
// Multi slice :name Slice name ,[] dimension , T type
var name [][]...[]T
// Two dimensional slices
var c = [][]int{
{
1}, {
2, 3}}
fmt.Println("c[0][0] ", c[0][0])
fmt.Println("c[1][0] ", c[1][0])
// result
c[0][0] 1
c[1][0] 2
5. function
len() and cap() function
len() Method to get the length
cap() Method to calculate the maximum length of slices
len and cap It's not equal
package main
import "fmt"
func main() {
var num = make([]int, 2, 10)
fmt.Printf("len=%d cap=%d slice=%v\n", len(num), cap(num), num)
}
// result
len=2 cap=10 slice=[0 0]
append() function
append Dynamically add elements to slices , Then return a slice of the same type as the slice .
When there is not enough space to hold enough elements , The slice will press 2 Multiple expansion of .
Slice insert from start element , It will cause existing elements to be copied once , Poor performance is not as good as tail insertion .
append(slice_name, value)
package main
import "fmt"
func main() {
var num = make([]int, 2, 10)
fmt.Printf("len=%d cap=%d slice=%v\n", len(num), cap(num), num)
num = append(num, 3, 4, 5, 6, 7, 8, 8, 9, 9, 6)
fmt.Printf("len=%d cap=%d slice=%v\n", len(num), cap(num), num)
// Add... To the head
num = append([]int{
100}, num...)
fmt.Printf("len=%d cap=%d slice=%v\n", len(num), cap(num), num)
}
// result
len=2 cap=10 slice=[0 0]
// cap change , It's expanded
len=12 cap=20 slice=[0 0 3 4 5 6 7 8 8 9 9 6]
// Added elements to the head 100
len=13 cap=14 slice=[100 0 0 3 4 5 6 7 8 8 9 9 6]
append Combine
append(slice_name,append(slice_name, value))
copy() function
copy function copy From source slice Of src Copy element to target dst, And return the number of elements copied
// dst Target slice , Can contain src section ,src Source slice ,dst and src The slice type should be the same . Return value : Element number
copy( dst, src []T) int
package main
import "fmt"
func main() {
// copy
s1 := []int{
1, 2, 3, 4, 5, 6}
s2 := []int{
9, 8, 7}
copy(s1, s2)
// Only copy s2 Before 3 Elements to s1 in ,s1 The first three of are replaced
fmt.Println("s1:", s1)
copy(s2, s1)
// s2 Can't hold s1, Not copied s1
fmt.Println("s2:", s2)
}
// result
s1: [9 8 7 4 5 6]
s2: [9 8 7]
Slice as a parameter
Read Functions can accept slice parameters instead of pointers and counts ; The length in the slice sets the upper limit of the amount of data read .
// The buffer is buf section
func (f *File) Read(buf []byte) (n int, err error)
var n int
var err error
for i := 0; i < 32; i++ {
nbytes, e := f.Read(buf[i:i+1]) // Read one byte.
n += nbytes
if nbytes == 0 || e != nil {
err = e
break
}
}
边栏推荐
- 输入cnpm -v出现cnpm : 无法加载文件 C:\Users\19457\AppData\Roaming\npm\cnpm.ps1,因为在此系统上禁止运行脚本。
- 1000 okaleido tiger launched binance NFT, triggering a rush to buy
- Cinq ans de contact avec près d'une centaine de patrons, en tant que chasseur de têtes, j'a i découvert que le secret de la promotion n'est que quatre mots
- How CAD draws arrows with arcs
- In depth understanding of the underlying framework of wechat applet (II) component system, exprser
- Phpcms realizes product multi condition screening function
- NETCORE - how to ensure that icollection or list privatization is not externally modified?
- “我们为什么要做 iVX ? ” ——访 iVX CEO 孟智平 了解 iVX 企业文化
- Sharing a case of controller restart caused by a CIFS bug in NetApp Fas series
- 深入了解-微信开发者工具
猜你喜欢

以科技传递温度,vivo守护生物多样性之美
![[重要通知]星球线上培训第三期来袭!讲解如何在QTYX上构建自己的量化策略!...](/img/37/f9ea9af069f62cadff21415f070223.png)
[重要通知]星球线上培训第三期来袭!讲解如何在QTYX上构建自己的量化策略!...

canvas-绘图(鼠标按下 绘制 抬起 结束)

Enter cnpm -v and cnpm appears: the file c:\users\19457\appdata\roaming\npm\cnpm.ps1 cannot be loaded because running scripts is prohibited on this system.

Ardunio - ULN2003 drive board and DC motor fan - control fan speed

Small volume stock trading record | based on multi task crawler technology, realize level1 sampling of A-share real-time market

After five years of contact with nearly 100 bosses, as a headhunter, I found that the secret of promotion was only four words
深入理解微信小程序的底层框架(二)组件系统、Exparser

Writing of graph nodes that trigger different special effects during the day and at night in Tiktok

解决script标签写在元素节点前面无法获取元素节点的问题
随机推荐
LeetCode 70爬楼梯、199二叉树的右视图、232用栈实现队列、143重排链表
Jar package used by jsonarray in main function provided by leetcode
Cinq ans de contact avec près d'une centaine de patrons, en tant que chasseur de têtes, j'a i découvert que le secret de la promotion n'est que quatre mots
5年接触近百位老板,身为猎头的我,发现升职的秘密不过4个字
解决script标签写在元素节点前面无法获取元素节点的问题
Webshell management tool and its traffic characteristics analysis
In depth understanding - wechat developer tools
145-keep-alive的初步使用
Leetcode 70 climbing stairs, 199 right view of binary tree, 232 realizing queue with stack, 143 rearranging linked list
Visual full link log tracking
响应式布局一个网页在不同设备显示不同效果)meta:vp
Ggplot2 displays png
[Luogu] p1972 HH Necklace
JDBC tool class
Jmeter+influxdb+grafana pressure measurement real-time monitoring platform construction
通过Arduino IDE向闪存文件系统上传文件
ASP. Net core write a cache attribute tool
Solve the problem that the script tag is written in front of the element node and cannot get the element node
什么叫裸写SQL?express操作mysql用什么中件间或插件好呢?
pbootcms模板调用标签序数从2开始或者自动数开始