简体   繁体   中英

Issues with string and .String() in Golang

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?

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)

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM