2

I can't understand the following behaviour in Go:

package main

import "fmt"

type Something string

func (a *Something) String() string {
  return "Bye"
}

func main() {
  a := Something("Hello")

  fmt.Printf("%s\n", a)
  fmt.Printf("%s\n", a.String())
}

Will output:

Hello
Bye

Somehow this feels kinda incosistent. Is this expected behaviour? Can someone help me out here?

2 Answers 2

4

Your String() is defined on the pointer but you're passing a value to Printf.

Either change it to:

func (Something) String() string {
    return "Bye"
}

or use

fmt.Printf("%s\n", &a)
Sign up to request clarification or add additional context in comments.

Comments

1

The arguments types are different. For example,

package main

import "fmt"

type Something string

func (a *Something) String() string {
    return "Bye"
}

func main() {
    a := Something("Hello")

    fmt.Printf("%T %s\n", a, a)
    fmt.Printf("%T %s\n", a.String(), a.String())
}

Output:

main.Something Hello
string Bye

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.