Three simple ways to use Golang slices and their differences

藏色散人
Release: 2020-09-29 13:31:08
forward
2064 people have browsed it

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!

Three simple ways to use Golang slices and their differences

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))
}
Copy after login

②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)

  1. You can specify the slice size and capacity when creating a slice through make.
  2. If no value is assigned to each element of the slice, the default value ( int, float=>0, strint=>"", bool=>false)
  3. 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}
Copy after login

③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}
Copy after login

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)
}
Copy after login
rrree

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!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!