gpt4 book ai didi

string - Golang 中字符串和 .String() 的问题

转载 作者:IT王子 更新时间:2023-10-29 01:33:50 24 4
gpt4 key购买 nike

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

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

最佳答案

您的 String() 是在指针上定义的,但您正在将一个值传递给 Printf

要么将其更改为:

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

或使用

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

关于string - Golang 中字符串和 .String() 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26278520/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com