int * time.Second何时工作,什么时候在golang中不工作? [英] When does `int * time.Second` work and when does it not in golang?

查看:87
本文介绍了int * time.Second何时工作,什么时候在golang中不工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 time.Sleep(5 * time.Second)可以正常工作,但是:

Why does time.Sleep(5 * time.Second) work fine, but:

x := 180
time.Sleep(15 / x * 60 * time.Second)

不是吗?我收到类型不匹配错误(类型为 int64 time.Duration ).鉴于错误,我更了解后者为何失败而不是原因为何成功.

does not? I get a type mismatch error (types int64 and time.Duration). Given the error, I understand more of why the latter fails than why the former succeeds.

推荐答案

在Go中,一个数字文字(例如 60 )是一个无类型常量 .这意味着它将被静默地强制为适用于使用该操作的任何类型.所以当你说:

In Go, a numeric literal (e.g. 60) is an untyped constant. That means it will be silently coerced to whatever type is appropriate for the operation where it's being used. So when you say:

var x := 5 * time.Second

然后从 time.Second 推断出类型为 time.Duration ,因此文字 5 也被视为 time.Duration .如果没有什么可以从中推断类型,它将假设一个类型(布尔,符文,整数,float64,complex128或字符串")并使用该类型.所以:

Then the type is inferred from time.Second to be a time.Duration, and thus the literal 5 is also treated as a time.Duration. If there's nothing to infer a type from, it will assume a type ("bool, rune, int, float64, complex128 or string") and use that. So:

x := 180

类型为 int x .

但是,当您执行涉及某种类型的东西的操作时,比如说变量 x int ,则您有两种类型,一种必须是转换为合法操作.

However, when you do some operation involving something with a type - like, say a variable x that is an int - then you have two types and one must be converted for the operation to be legal.

因此,对于最初的问题" int * time.Second 何时起作用,何时在golang中不起作用?", int * time.Second 实际上是从不在Go中工作.但是 5 * time.Second int * time.Second 不同.

So, to the original question "When does int * time.Second work and when does it not in golang?", int * time.Second actually never works in Go. But 5 * time.Second isn't the same as int * time.Second.

这已在围棋之旅中进行了提及:

无类型的常量采用其上下文所需的类型.

An untyped constant takes the type needed by its context.

这篇关于int * time.Second何时工作,什么时候在golang中不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆