1
votes

I'm trying to learn GO and naturally I have difficulty in basic stuff. I came across this recently in an example regarding IOTA however my question isn't about IOTA but about whats going on regarding the String() receiver function with a capital S.

Is there a technical / programming term for what we are doing with the function named String in this example? It has something to do with data type "string" but cannot understand. Why doesn't this code work when I change the name from String to anything else, even to string() with non capital letters?

I would like some programming terms regarding what we are doing so that I can google further, since all I have at the moment is "String function" which doesnt bring much on google.

 package main

import "fmt"

type Direction byte

const (
    North Direction = iota
    East
    South
    West
)

func (d Direction) String() string {
    switch d {
    case North:
        return fmt.Sprintf("North")
    case South:
        return fmt.Sprintf("South")
    case East:
        return fmt.Sprintf("East")
    case West:
        return fmt.Sprintf("West")
    default:
        return "other direction"
    }

}
func main() {
    north := North
    fmt.Println(north)

}
String is method for the type Direction. Methods are covered in The Tour of Go and Effective Go. See the fmt Stringer documentation and printing in Effective Go on the use of the String method by the fmt package. - Cerise Limón