Go – operator overloading

huangapple go评论75阅读模式
英文:

Go - operator overloading

问题

我已经开始学习Go,并且正在尝试理解下面的代码:

time.Sleep(1000 * time.Millisecond) // 正常工作
time.Sleep("1000ms") // 不工作

如果你将 time.Milliseconds 打印到控制台,你会看到 1ms。所以我认为我可以简单地使用值 "1000ms" 调用该方法,但是我得到了一个错误。接下来,我搜索了Go中的运算符重载,但是它不支持。我理解 time.Sleep 接受 time.Milliseconds 数据类型,但是如果Go不支持像 * 这样的运算符重载,它是如何实现的呢?

英文:

I have started to study Go and I am trying to understand what happens below:

<!-- language: lang-go -->

time.Sleep(1000 * time.Millisecond) // Works
time.Sleep(&quot;1000ms&quot;) // Doesn&#39;t work

<!-- end snippet -->

If you print to the console time.Milliseconds you can see 1ms. So I think that I can simply call that method with the value &quot;1000ms&quot;, but I get an error. Next I searched for operator overloading in Go, but it doesn't support it. I understand that time.Sleep gets the time.Milliseconds data type, but how does Go allow it if it doesn't support overloading operators like *?

答案1

得分: 5

Sleep()接受一个Duration类型的参数,该类型是int64。因此,如果不将字符串类型的对象进行类型转换,你无法将其作为参数传递。

你之所以得到输出1ms,是因为使用了以下方法:

(time.Duration) String() string
英文:

Sleep() accept a Duration type which is int64. So you can't pass string type object as an argument without typecasting it.

You got the output 1ms because of this method

(time.Duration) String() string

huangapple
  • 本文由 发表于 2017年4月2日 00:02:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/43159021.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定