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.
是否有fmt.Print`将使用的等效于ToString()的Go?
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- doufu1970 2016-12-20 00:05关注
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 aStringer()
interface themselves becausefmt.Println("foo")
andfmt.Println(someStringer)
are equally valid. I recommend you go through theprint.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.
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 - accept an
悬赏问题
- ¥15 flink cdc无法实时同步mysql数据
- ¥100 有人会搭建GPT-J-6B框架吗?有偿
- ¥15 求差集那个函数有问题,有无佬可以解决
- ¥15 【提问】基于Invest的水源涵养
- ¥20 微信网友居然可以通过vx号找到我绑的手机号
- ¥15 寻一个支付宝扫码远程授权登录的软件助手app
- ¥15 解riccati方程组
- ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
- ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
- ¥50 树莓派安卓APK系统签名