Go by Example: Slices

本文介绍了Go语言中的切片类型,包括如何创建切片、设置和获取元素值、使用内置函数len获取长度、使用append函数追加元素、从一个切片拷贝元素到另一个切片以及切片操作等。此外,还介绍了如何声明和初始化多维切片。

切片是Go语言的关键类型之一,它提供了比数组更加强大的队列相关接口。


package main

import "fmt"

func main() {

    // 和数组不同的是,切片的类型仅由它所包含的元素决定。
    // 使用内置函数make可以创建一个长度不为零的切片。
    // 下面创建了一个长度为3,存储字符串的切片,
    // 切片元素默认为零值,对于字符串就是""。
    s := make([]string, 3)
    fmt.Println("emp:", s)

    // 和数组一样可以使用<strong>index</strong>来设置元素值或获取元素值
    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)
}
尽管切片和数据是不同的类型,但是使用 fmt.Println 输出时候格式相似。

$ go run slices.go
emp: [  ]
set: [a b c]
get: c
len: 3
apd: [a b c d e f]
cpy: [a b c d e f]
sl1: [c d e]
sl2: [a b c d e]
sl3: [c d e f]
dcl: [g h i]
2d:  [[0] [1 2] [2 3 4]]

我们已经了解了数组和切片,接下来我们将会介绍Go语言的另外一个内建的数据结构:Maps。

要了解更多关于切片,请查看学习Golang语言(6): 类型--切片

下一个例子: Go by Example:  Maps.


英文原文

07-18
Go2 is an informal term often used to refer to the next generation of features and updates in the Go programming language. While there isn't a formal release called "Go 2," the Go team and community have been working on significant improvements and new features that may be considered part of the evolution towards what some call Go2. Below are some key aspects and proposals that represent the direction of Go's future development: - **Generics**: One of the most anticipated features in Go is support for generics, which allows developers to write more reusable and type-safe code. Although Go currently lacks built-in support for generics, several third-party tools and libraries attempt to fill this gap by using code generation techniques[^3]. - **Error Handling Enhancements**: Improvements to error handling were proposed to make it less verbose while maintaining clarity and explicitness. The goal is to reduce boilerplate code associated with checking errors without compromising safety. - **Contracts and Type Parameters**: As part of the generics discussion, contracts (also known as constraints) have been suggested as a way to specify what operations types must support when used as type parameters. This would allow functions written with generic type parameters to enforce certain behaviors on those types. - **Improved Module Support**: With modules introduced in Go 1.11, dependency management became much easier. Future plans include further refinements to module functionality, such as better proxy support, improved versioning semantics, and enhanced tooling around module usage. - **Better Tooling Integration**: Continued enhancement of tools like `gopls`, the Go Language Server, aims at providing richer IDE integrations, faster indexing, and overall smarter tooling around Go development environments. - **Concurrency Enhancements**: Although Go already provides powerful concurrency primitives through goroutines and channels, discussions continue about how these could evolve to handle increasingly complex concurrent scenarios efficiently and safely. - **Embedding Capabilities**: Go has made strides in enabling embedding capabilities within applications, allowing scripts written in other languages like Lua or JavaScript to be executed directly from Go programs. Libraries such as `anko` and `otto` facilitate scripting functionalities inside Go applications[^1]. These developments reflect ongoing efforts to keep Go competitive and relevant amidst evolving software development needs. However, any major changes undergo rigorous scrutiny to ensure they align well with Go’s core principles of simplicity, efficiency, and readability. ```go // Example placeholder function demonstrating potential syntax if generics were natively supported func Map[T any, U any](slice []T, f func(T) U) []U { result := make([]U, len(slice)) for i, v := range slice { result[i] = f(v) } return result } ``` This example uses hypothetical syntax for generics which might become standard in future versions of Go, illustrating how one could define a generic mapping function over slices.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值