0

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?

icza
  • 389,944
  • 63
  • 907
  • 827
pandith padaya
  • 1,643
  • 1
  • 10
  • 20
  • Going through the complete [Tour of Go](https://tour.golang.org/) might help establish the language fundamentals. – Adrian Mar 20 '20 at 16:10

3 Answers3

5

[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 dth 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'

icza
  • 389,944
  • 63
  • 907
  • 827
3

This part declares an array literal with four strings:

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

Then this part gets the dth element from the array:

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

Direction has to be int for this to work.

Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
1

@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]
}
Tiya Jose
  • 1,359
  • 14
  • 24
  • 1
    Complete code +1. A simpler version https://play.golang.org/p/j8BN7sLsmjt. –  Oct 15 '20 at 03:42