Three simple ways to use Golang slices and their differences
The following is the golang tutorial column about three simple ways to use Golang slices and their differences. I hope it will be helpful to friends in need!
Concept
Slice is based on arrays which is more convenient, more flexible and more powerful data structure. A slice does not store any elements but only a reference to an existing array.
Three methods and detailed cases
①Define a slice, and then let the slice reference an already created array
package main import ( "fmt") func main() { var arr [5]int = [...]int {1, 2, 3, 4, 5} var slice = arr[1:3] fmt.Println("arr=", arr) fmt.Println("slice=", slice) fmt.Println("slice len", len(slice)) fmt.Println("slice cap", cap(slice)) }
②Create slices through make. Basic syntax: var slice name []type = make([], len, [cap]); parameter description: type is the data type, len is the size, and cap is the slice capacity (capacity must be >= length)
- You can specify the slice size and capacity when creating a slice through make.
- If no value is assigned to each element of the slice, the default value ( int, float=>0, strint=>"", bool=>false)
- The array corresponding to the slice created by Rongguo make method is maintained by the bottom layer of make and is external Invisible, that is, each element can only be accessed through slice
package main import ( "fmt") func main() { var slice []float64 = make([]float64, 5, 10) //没有给值,默认都是0 fmt.Println(slice) //[0 0 0 0 0] //赋值 slice[1] = 5 slice[3] = 10 fmt.Println(slice) //[0 5 0 10 0] fmt.Println("slice大小:", len(slice)) //slice大小: 5 fmt.Println("slice容量:", cap(slice)) //slice容量: 10}
③Define a slice and directly specify the specific array. The usage principle is similar to make
package main import ( "fmt") func main() { var slice []string = []string{"zhangsan", "lisi", "wangwu"} fmt.Println("slice=", slice) //slice= [zhangsan lisi wangwu] fmt.Println("slice len", len(slice)) //slice len 3 fmt.Println("slice cap", cap(slice)) //slice cap 3}
The difference between the first and second method
The first way is to directly reference the array. This array exists in advance and is visible to the programmer
The second way is to create a slice through make. Make will also create an array, which is maintained by the slice at the bottom and is invisible to the programmer.
Supplement : Fragmentary cases
package main import "fmt"func main() { // 和数组不同的是,切片的长度是可变的。 // 我们可以使用内置函数make来创建一个长度不为零的切片 // 这里我们创建了一个长度为3,存储字符串的切片,切片元素 // 默认为零值,对于字符串就是""。 s := make([]string, 3) fmt.Println("emp:", s) // 可以使用和数组一样的方法来设置元素值或获取元素值 s[0] = "a" s[1] = "b" s[2] = "c" fmt.Println("set:", s) fmt.Println("get:", s[2]) // 可以用内置函数len获取切片的长度 fmt.Println("len:", len(s)) // 切片还拥有一些数组所没有的功能。 // 例如我们可以使用内置函数append给切片追加值,然后 // 返回一个拥有新切片元素的切片。 // 注意append函数不会改变原切片,而是生成了一个新切片, // 我们需要用原来的切片来接收这个新切片 s = append(s, "d") s = append(s, "e", "f") fmt.Println("apd:", s) // 另外我们还可以从一个切片拷贝元素到另一个切片 // 下面的例子就是创建了一个和切片s长度相同的新切片 // 然后使用内置的copy函数来拷贝s的元素到c中。 c := make([]string, len(s)) copy(c, s) fmt.Println("cpy:", c) // 切片还支持一个取切片的操作 "slice[low:high]" // 获取的新切片包含元素"slice[low]",但是不包含"slice[high]" // 下面的例子就是取一个新切片,元素包括"s[2]","s[3]","s[4]"。 l := s[2:5] fmt.Println("sl1:", l) // 如果省略low,默认从0开始,不包括"slice[high]"元素 l = s[:5] fmt.Println("sl2:", l) // 如果省略high,默认为len(slice),包括"slice[low]"元素 l = s[2:] fmt.Println("sl3:", l) // 我们可以同时声明和初始化一个切片 t := []string{"g", "h", "i"} fmt.Println("dcl:", t) // 我们也可以创建多维切片,和数组不同的是,切片元素的长度也是可变的。 twoD := make([][]int, 3) for i := 0; i < 3; i++ { innerLen := i + 1 twoD[i] = make([]int, innerLen) for j := 0; j < innerLen; j++ { twoD[i][j] = i + j } } fmt.Println("2d: ", twoD) }
The above is the detailed content of Three simple ways to use Golang slices and their differences. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Reading and writing files safely in Go is crucial. Guidelines include: Checking file permissions Closing files using defer Validating file paths Using context timeouts Following these guidelines ensures the security of your data and the robustness of your application.

How to configure connection pooling for Go database connections? Use the DB type in the database/sql package to create a database connection; set MaxOpenConns to control the maximum number of concurrent connections; set MaxIdleConns to set the maximum number of idle connections; set ConnMaxLifetime to control the maximum life cycle of the connection.

The difference between the GoLang framework and the Go framework is reflected in the internal architecture and external features. The GoLang framework is based on the Go standard library and extends its functionality, while the Go framework consists of independent libraries to achieve specific purposes. The GoLang framework is more flexible and the Go framework is easier to use. The GoLang framework has a slight advantage in performance, and the Go framework is more scalable. Case: gin-gonic (Go framework) is used to build REST API, while Echo (GoLang framework) is used to build web applications.

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

The FindStringSubmatch function finds the first substring matched by a regular expression: the function returns a slice containing the matching substring, with the first element being the entire matched string and subsequent elements being individual substrings. Code example: regexp.FindStringSubmatch(text,pattern) returns a slice of matching substrings. Practical case: It can be used to match the domain name in the email address, for example: email:="user@example.com", pattern:=@([^\s]+)$ to get the domain name match[1].

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

Using predefined time zones in Go includes the following steps: Import the "time" package. Load a specific time zone through the LoadLocation function. Use the loaded time zone in operations such as creating Time objects, parsing time strings, and performing date and time conversions. Compare dates using different time zones to illustrate the application of the predefined time zone feature.

Go framework development FAQ: Framework selection: Depends on application requirements and developer preferences, such as Gin (API), Echo (extensible), Beego (ORM), Iris (performance). Installation and use: Use the gomod command to install, import the framework and use it. Database interaction: Use ORM libraries, such as gorm, to establish database connections and operations. Authentication and authorization: Use session management and authentication middleware such as gin-contrib/sessions. Practical case: Use the Gin framework to build a simple blog API that provides POST, GET and other functions.
