search
HomeBackend DevelopmentGolangThree 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!

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

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

③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 rrree<p> </p>

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!

Statement
This article is reproduced at:cnblogs. If there is any infringement, please contact admin@php.cn delete
Golang and Python: Understanding the DifferencesGolang and Python: Understanding the DifferencesApr 18, 2025 am 12:21 AM

The main differences between Golang and Python are concurrency models, type systems, performance and execution speed. 1. Golang uses the CSP model, which is suitable for high concurrent tasks; Python relies on multi-threading and GIL, which is suitable for I/O-intensive tasks. 2. Golang is a static type, and Python is a dynamic type. 3. Golang compiled language execution speed is fast, and Python interpreted language development is fast.

Golang vs. C  : Assessing the Speed DifferenceGolang vs. C : Assessing the Speed DifferenceApr 18, 2025 am 12:20 AM

Golang is usually slower than C, but Golang has more advantages in concurrent programming and development efficiency: 1) Golang's garbage collection and concurrency model makes it perform well in high concurrency scenarios; 2) C obtains higher performance through manual memory management and hardware optimization, but has higher development complexity.

Golang: A Key Language for Cloud Computing and DevOpsGolang: A Key Language for Cloud Computing and DevOpsApr 18, 2025 am 12:18 AM

Golang is widely used in cloud computing and DevOps, and its advantages lie in simplicity, efficiency and concurrent programming capabilities. 1) In cloud computing, Golang efficiently handles concurrent requests through goroutine and channel mechanisms. 2) In DevOps, Golang's fast compilation and cross-platform features make it the first choice for automation tools.

Golang and C  : Understanding Execution EfficiencyGolang and C : Understanding Execution EfficiencyApr 18, 2025 am 12:16 AM

Golang and C each have their own advantages in performance efficiency. 1) Golang improves efficiency through goroutine and garbage collection, but may introduce pause time. 2) C realizes high performance through manual memory management and optimization, but developers need to deal with memory leaks and other issues. When choosing, you need to consider project requirements and team technology stack.

Golang vs. Python: Concurrency and MultithreadingGolang vs. Python: Concurrency and MultithreadingApr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

Golang and C  : The Trade-offs in PerformanceGolang and C : The Trade-offs in PerformanceApr 17, 2025 am 12:18 AM

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

Golang vs. Python: Applications and Use CasesGolang vs. Python: Applications and Use CasesApr 17, 2025 am 12:17 AM

ChooseGolangforhighperformanceandconcurrency,idealforbackendservicesandnetworkprogramming;selectPythonforrapiddevelopment,datascience,andmachinelearningduetoitsversatilityandextensivelibraries.

Golang vs. Python: Key Differences and SimilaritiesGolang vs. Python: Key Differences and SimilaritiesApr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor