dqol6556 2018-12-18 16:20
浏览 21
已采纳

函数自动执行而不被调用

I started to learn Go yesterday on the Tour of Go website and I thought that I was understanding everything well;

But then I was totally confused on the exercise Stringers: https://tour.golang.org/methods/18

So I searched a solution to see what I was doing wrong and I found this:

package main

import "fmt"

type IPAddr [4]byte

// TODO: Add a "String() string" method to IPAddr.

func (i IPAddr) String() string {
    return fmt.Sprintf("%d.%d.%d.%d", i[0], i[1], i[2], i[3])   

 }

func main() {
    hosts := map[string]IPAddr{
        "loopback":  {127, 0, 0, 1},
        "googleDNS": {8, 8, 8, 8},
    }
    for name, ip := range hosts {
        fmt.Printf("%v: %v
", name, ip)
    }
}

and the output is this:

loopback: 127.0.0.1
googleDNS: 8.8.8.8

it left me completely confused;

Why did the function activate itself? Should'nt it be like: i.String() inside the main func?

Why did the fmt.Printf show nothing on the screen at all?

Or the fmt.Printf returned that because the String() changed the value?

I'm sorry if the question is confusing, but can someone explain this to me?

展开全部

  • 写回答

1条回答 默认 最新

  • duankuai6991 2018-12-18 16:30
    关注

    If you look at the previous page in the tutorial, you see that Stringer is an interface defined in the fmt package. Implementing the String() method automatically makes IPAddr implement this interface.

    The fmt.Printf function checks if its argument implements the Stringer interface. Since it now does, it calls the String method when it needs to figure out how to show an IPAddress (you can change this behavior by using a format specifier other than %v, but that's beyond the scope of the question).

    The fmt.Printf call showed something; it showed the lines

    loopback: 127.0.0.1
    googleDNS: 8.8.8.8
    

    It didn't change their value or anything; it just called the String method to figure out how to write down an IPAddr, and wrote it down that way.

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

报告相同问题?

悬赏问题

  • ¥15 KeiI中头文件找不到怎么解决
  • ¥15 QT6将音频采样数据转PCM
  • ¥15 本地安装org.Hs.eg.dby一直这样的图片报错如何解决?
  • ¥15 下面三个文件分别是OFDM波形的数据,我的思路公式和我写的成像算法代码,有没有人能帮我改一改,如何解决?
  • ¥15 Ubuntu打开gazebo模型调不出来,如何解决?
  • ¥100 有chang请一位会arm和dsp的朋友解读一个工程
  • ¥50 求代做一个阿里云百炼的小实验
  • ¥15 查询优化:A表100000行,B表2000 行,内存页大小只有20页,运行时3页,设计两个表等值连接的最简单的算法
  • ¥15 led数码显示控制(标签-流程图)
  • ¥20 为什么在复位后出现错误帧
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部