gpt4 book ai didi

go - time.Millisecond * int 混淆

转载 作者:IT王子 更新时间:2023-10-29 01:47:59 25 4
gpt4 key购买 nike

在下面的示例中,如果 1000 都是整数(我认为它们是),为什么底部无法编译?

//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.

例如,使用“*”(乘法)运算符,

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)
}

关于go - time.Millisecond * int 混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35544345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com