Int (const and nonconst) to time.duration This is a common operation, but we encounter a problem in the following code that is confusing to beginners. Here we simply ‘root’ it

The problem

``` package main import ( "fmt" "reflect" "time" ) const a = 1 func test(a time.Duration) { fmt.Printf("%v \n", a) } func main() { b := a + 1 fmt.Printf("---- a = %v \n", reflect.TypeOf(a)) test(a) fmt.Printf("---- b = %v \n", Reflect the TypeOf (b)) / / test (b) / / > open after the comments, will compile without} ` ` `Copy the code

For reasons (official documentation, seereference)

Assignability
	A value x is assignable to a variable of type T ("x is assignable to T") if one of the following conditions applies:
		- x's type is identical to T.
		- x's type V and T have identical underlying types and at least one of V or T is not a defined type.
		- T is an interface type and x implements T.
		- x is a bidirectional channel value, T is a channel type, x's type V and T have identical element types, and at least one of V or T is not a defined type.
		- x is the predeclared identifier nil and T is a pointer, function, slice, map, channel, or interface type.
		- x is an untyped constant representable by a value of type T.	
Copy the code

That is, when a const variable is not explicitly typed, it is cast as needed. Variables that are not const do not. This explains the confusion in the above code.

Reference

  • Golang.org/ref/spec#Co…

Welcome to exchange and learn ~