我是golang的新手,有一个基本问题。我的以下代码摘自网络示例
func (d Direction) String() string {
return [...]string{"North", "East", "South", "West"}[d]
}
我很困惑[d]
在方法主体中做什么?
答案 0 :(得分:5)
[d]
只是一个index expression,它索引在其前面带有array的composite literal。
此:
[...]string{"North", "East", "South", "West"}
是一个数组复合文字,它使用列出的元素创建元素类型为string
的数组,随后的[d]
对该数组进行索引。该方法返回此4大小数组的d
th 元素。
请注意,...
意味着我们希望编译器自动确定数组大小:
符号
...
指定的数组长度等于最大元素索引加一。
不要将slices误认为Go中的数组。有关数组和切片的良好介绍,请阅读官方博客文章:
The Go Blog: Go Slices: usage and internals
The Go Blog: Arrays, slices (and strings): The mechanics of 'append'
答案 1 :(得分:3)
这部分声明一个带有四个字符串的数组文字:
[...]string{"North", "East", "South", "West"}
然后这部分从数组中获取第d
个元素:
[...]string{"North", "East", "South", "West"}[d]
Direction
必须是int
才能起作用。
答案 2 :(得分:2)
@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]
}