【问题标题】:Golang, what does the following do []Golang,下面是做什么的[]
【发布时间】:2020-03-19 21:07:11
【问题描述】:

我是 golang 新手,有一个基本问题。我有以下代码取自网络上的示例

func (d Direction) String() string {
    return [...]string{"North", "East", "South", "West"}[d]
}

我很困惑[d] 在方法体中做了什么?

【问题讨论】:

  • 阅读完整的Tour of Go 可能有助于建立语言基础。

标签: arrays go composite-literals


【解决方案1】:

[d] 只是一个index expression,它索引前面带有composite literalarray

这个:

[...]string{"North", "East", "South", "West"}

是一个数组复合字面量,它使用列出的元素创建一个元素类型为string 的数组,随后的[d] 索引这个数组。该方法返回这个 4 大小数组的 dth 元素。

注意... 表示我们希望编译器自动确定数组大小:

符号... 指定数组长度等于最大元素索引加一。

不要将 Go 中的数组与 slices 混淆。有关数组和切片的详细介绍,请阅读官方博客文章:

The Go Blog: Go Slices: usage and internals

The Go Blog: Arrays, slices (and strings): The mechanics of 'append'

【讨论】:

    【解决方案2】:

    这部分声明了一个包含四个字符串的数组字面量:

    [...]string{"North", "East", "South", "West"}
    

    然后这部分从数组中获取dth 元素:

    [...]string{"North", "East", "South", "West"}[d]
    

    Direction 必须是 int 才能正常工作。

    【讨论】:

      【解决方案3】:

      @icza 和@Burak Serdar 提到 [d] 是一个索引表达式。

      以下只是一个查看输出的工作示例

      package main
      
      import "fmt"
      
      type Direction int
      
      func (d Direction) String() string {
          return [...]string{"North", "East", "South", "West"}[d]
      }
      
      func main() {
          n:=Direction(0)  // d=0
          fmt.Println(n)
          w:=Direction(3)  // d=3
          fmt.Println(w)
      }
      

      输出:

      North
      West
      

      为了更清楚,

      return [...]string{"North", "East", "South", "West"}[d]

      可以扩展为

      func (d Direction) String() string {
          var directions = [...]string{"North", "East", "South", "West"}
          return directions[d]
      }
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      • 1970-01-01
      相关资源
      最近更新 更多