英文:
Is there a Go equivalent of `ToString()` that `fmt.Print` will use?
问题
我在文档中查找了,但没有找到这个信息。
给定一个结构体,是否可以实现一个方法(比如 func (k Koala) String() string
),在打印结构体时自动被 fmt.Print
系列函数使用?
也许有一个接口可以实现这个功能,但我没有找到。
英文:
I've looked in the documentation and couldn't find this info.
Given a struct, is it possible to implement a method (say, func (k Koala) String() string
) that will automatically be used by the fmt.Print
family when printing a struct?
Maybe there's an interface somewhere, but I didn't find it.
答案1
得分: 7
是的,它被称为fmt.Stringer()
。
Stringer接口由具有String方法的任何值实现,该方法定义了该值的“本地”格式。String方法用于打印作为操作数传递给接受字符串的任何格式或传递给未格式化打印机(如Print)的值。
type Stringer interface {
String() string
}
*print*
函数本身不接受Stringer()
接口,因为fmt.Println("foo")
和fmt.Println(someStringer)
都是有效的。我建议您查看print.go
源代码以了解这是如何工作的,但简要来说,*print*
函数:
- 接受一个
interface{}
参数; - 检查它是否是内置类型(例如
string
、int
等),如果是,则相应地进行格式化; - 检查类型是否具有
.String()
方法,如果存在,则使用该方法。
具体的逻辑稍微复杂一些。正如我之前提到的,我鼓励您自己查看源代码。它完全是可读的Go代码。
英文:
Yes, it's called fmt.Stringer()
> Stringer is implemented by any value that has a String method, which defines the “native” format for that value. The String method is used to print values passed as an operand to any format that accepts a string or to an unformatted printer such as Print.
> type Stringer interface {
String() string
}
The *print*
functions don't accept a Stringer()
interface themselves because fmt.Println("foo")
and fmt.Println(someStringer)
are equally valid. I recommend you go through the print.go
source code to see exactly how this works, but in brief the *print*
functions:
- accept an
interface{}
; - check if it's a built-in type (e.g.
string
,int
, etc.) and format it accordingly if it is; - check if the type has a
.String()
method and use that if it exists.
The precise logic is a bit more involved. As mentioned, I encourage you to go through the source code yourself. It's all just plain readable Go.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论