time.Millisecond * int confusion

前端 未结 5 508
臣服心动
臣服心动 2020-12-18 20:12

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


        
相关标签:
5条回答
  • 2020-12-18 20:50

    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)
    }
    
    0 讨论(0)
  • 2020-12-18 20:50

    Go won't convert numeric types automatically for you. As far as I understand, 1000 isn't a numeric type until defined as one.

    The language specification says:

    Conversions are required when different numeric types are mixed in an expression or assignment. For instance, int32 and int are not the same type even though they may have the same size on a particular architecture.

    0 讨论(0)
  • 2020-12-18 20:51

    You can make i a constant instead of a variable, if you are primarily interested in naming the value:

    package main
    
    import (
        "time"
    )
    
    func main() {
        // works:
        time.Sleep(1000 * time.Millisecond)
    
        // works also:
        const i = 1000
        time.Sleep(i * time.Millisecond)
    }
    

    In-reply-to: https://stackoverflow.com/a/19338130/11630268

    0 讨论(0)
  • 2020-12-18 20:55

    You should convert to time.Duration (which underneath is an int64)

    var i = 1000
    time.Sleep(time.Duration(i) * time.Millisecond)
    
    0 讨论(0)
  • 2020-12-18 21:11

    Both operants need to be of the same type time.Duration. You can use time.Sleep(v * time.Millisecond).

    0 讨论(0)
提交回复
热议问题