duana1986 2016-12-19 23:59
浏览 18
已采纳

是否有fmt.Print`将使用的等效于ToString()的Go?

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条回答 默认 最新

  • 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 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥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系统签名