Golang中的字符串和.String()存在的问题

huangapple go评论80阅读模式
英文:

Issues with string and .String() in Golang

问题

我无法理解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())
}

输出结果为:

Hello
Bye

不知何故,这种行为感觉有点不一致。这是预期的行为吗?有人可以帮我解决这个问题吗?

英文:

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?

答案1

得分: 4

你的String()方法是在指针上定义的,但你却将一个值传递给了Printf函数。

你可以选择将其改为:

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

或者使用:

fmt.Printf("%s\n", &a)
英文:

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)

答案2

得分: 1

参数类型不同。例如,

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())
}

输出:

main.Something Hello
string Bye
英文:

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

huangapple
  • 本文由 发表于 2014年10月9日 20:31:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/26278520.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定