当前位置:网站首页>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
}
}
边栏推荐
- How CAD draws arrows with arcs
- How to do a good job of accompanying translation
- 浅谈领域驱动设计
- 浅谈元宇宙中DeFi的可能性和局限性
- Diablo king, analysis of low illumination image enhancement technology
- Phpcms realizes product multi condition screening function
- Reconnaître le Protocole de couche de transport - TCP / UDP
- 使用第三方账号登录
- [important notice] the third phase of planet online training is coming! Explain how to build your own quantitative strategy on qtyx
- Use the hiflow scene connector to view the epidemic situation in the region every day
猜你喜欢

Sharing a case of controller restart caused by a CIFS bug in NetApp Fas series

Visual full link log tracking

1000 okaleido tiger launched binance NFT, triggering a rush to buy

Network protocol details: UDP

JDBC tool class

NetApp FAS系列一个CIFS bug引起的控制器重启案例分享

View binding confusion. I have been studying confusion for two days.
![[C language operation of linked list (initialization, establishment, length calculation, addition, deletion, and output of linked list)]](/img/9b/e5cda39c04d0cc2f69e43c97ee997d.png)
[C language operation of linked list (initialization, establishment, length calculation, addition, deletion, and output of linked list)]

5年接触近百位老板,身为猎头的我,发现升职的秘密不过4个字

Phpcms realizes product multi condition screening function
随机推荐
[Luogu] p1972 HH Necklace
关于 SAP Fiori 应用的离线使用
Cmake Getting Started tutorial
文心大模型扬起新“帆”,产业应用大潮已至
Go基础笔记_5_数组切片
Redis 6.0 source code learning simple dynamic string
jmeter+influxdb+grafana压测实时监控平台搭建
Halide::Generator生成器使用说明
Performance test of ArrayList and LinkedList insertion based on jmh
[Luogu] p1318 ponding area
The combination sum of C language power deduction question 39. Backtracking method and traversal method
Is software testing still popular in 2022?
Codeworks 5 questions per day (average 1500) - day 23
C language curriculum - personal information management system (including student grades and consumption records)
1000个Okaleido Tiger首发上线Binance NFT,引发抢购热潮
Ardunio - ULN2003 drive board and DC motor fan - control fan speed
In depth understanding of the underlying framework of wechat applet (II) component system, exprser
解决script标签写在元素节点前面无法获取元素节点的问题
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
[MySQL] character set utf8mb4 cannot store the record of expression stepping on the pit