英文:
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("1000ms") // Doesn'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 "1000ms"
, 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论