time.Millisecond * int混淆 [英] time.Millisecond * int confusion

查看:495
本文介绍了time.Millisecond * int混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的例子中,如果1000都是int(我认为它们是),为什么底部不能编译?

  //工作
time.Sleep(1000 * time.Millisecond)

//失败
var i = 1000
time.Sleep(i * time .Millisecond)


解决方案


< a href =http://golang.org/ref/spec#Operators =noreferrer>运算符



运算符将操作数组合到表达式中。

比较在其他地方讨论。对于其他二元运算符,
操作数类型必须相同,除非该操作涉及到
或无类型常量。对于仅涉及常量的操作,请参阅常量表达式的
部分。除了移位操作外,如果一个操作数是一个无类型常量而
,另一个操作数不是,则该常量被转换为$ b $的类型b其他操作数。

例如,使用 * (乘法)运营商,

 包主

导入(
时间


func main(){

//作品 - 1000是一个无类型常量
//被转换为类型time.Duration
time .Sleep(1000 * time.Millisecond)

//失败 - v是一个类型为int
的变量//它与类型time.Duration不相同
var v = 1000
//无效操作:i * time.Millisecond(不匹配类型int和time.Duration)
time.Sleep(v * time.Millisecond)
}


In the below example, if the 1000's are both int's (which I think they are) why would the bottom fail to compile?

//works
time.Sleep(1000 * time.Millisecond)

//fails
var i = 1000
time.Sleep(i * time.Millisecond)

解决方案

Operators

Operators combine operands into expressions.

Comparisons are discussed elsewhere. For other binary operators, the operand types must be identical unless the operation involves shifts or untyped constants. For operations involving constants only, see the section on constant expressions.

Except for shift operations, if one operand is an untyped constant and the other operand is not, the constant is converted to the type of the other operand.

For example, using the "*" (multiplication) operator,

package main

import (
    "time"
)

func main() {

    // works - 1000 is an untyped constant
    // which is converted to type time.Duration
    time.Sleep(1000 * time.Millisecond)

    // fails - v is a variable of type int
    // which is not identical to type time.Duration
    var v = 1000
    // invalid operation: i * time.Millisecond (mismatched types int and time.Duration)
    time.Sleep(v * time.Millisecond)
}

这篇关于time.Millisecond * int混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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