Golang中的string和.String()问题

问题描述:

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
", a)
  fmt.Printf("%s
", a.String())
}

Will output:

Hello
Bye

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

我无法理解Go中的以下行为: p>

 包main 
 
import“ fmt” 
 
type字符串
 
func(一个*东西)String()字符串{
返回“再见” 
} 
 
func main(){
a:  = Something(“ Hello”)
 
 fmt.Printf(“%s 
”,a)
 fmt.Printf(“%s 
”,a.String())
} 
  n   code>  pre> 
 
 

将输出: p>

  Hello 
Bye 
  code>  pre> 
 
 

不知何故,这有点令人发指。 这是预期的行为吗? 有人可以帮我吗? p> div>

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
", &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
", a, a)
    fmt.Printf("%T %s
", a.String(), a.String())
}

Output:

main.Something Hello
string Bye