I'm new to golang and have a basic question. I have the following code taken from an example from the web
func (d Direction) String() string {
return [...]string{"North", "East", "South", "West"}[d]
}
I'm confused what does the [d]
do in the method body?
[d]
is simply an index expression , it indexes the array created with a composite literal preceding it.
This:
[...]string{"North", "East", "South", "West"}
Is an array composite literal, it creates an array of element type string
with the listed elements, and the subsequent [d]
indexes this array. The method returns the d
th element of this 4-sized array.
Note that the ...
means we want the compiler to determine the array size automatically:
The notation
...
specifies an array length equal to the maximum element index plus one.
Arrays in Go is not to be mistaken with slices . For a good introduction on arrays and slices, read the official blog posts:
The Go Blog: Go Slices: usage and internals
The Go Blog: Arrays, slices (and strings): The mechanics of 'append'
This part declares an array literal with four strings:
[...]string{"North", "East", "South", "West"}
Then this part gets the d
th element from the array:
[...]string{"North", "East", "South", "West"}[d]
Direction
has to be int
for this to work.
@icza and @Burak Serdar have mentioned that [d] is an index expression.
Following is just a working example to see the output
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)
}
Output:
North
West
To be more clear,
return [...]string{"North", "East", "South", "West"}[d]
can be expanded as
func (d Direction) String() string {
var directions = [...]string{"North", "East", "South", "West"}
return directions[d]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.