Use int as month when building golang date

When I put int as an argument to time.Date for month , it works ( Example ):

 time.Date(2016, 1, 1, 0, 0, 0, 0, time.UTC) 

Why, when I try to convert string to int , and then use this variable, I get an error:

 cannot use mStr (type int) as type time.Month in argument to time.Date 

Example: https://play.golang.org/p/-XFNZHK476

+6
source share
3 answers

You need to convert the value to the appropriate type:

 import( "fmt" "time" "strconv" ) func main() { var m, _ = strconv.Atoi("01") // Now convert m to type time.Month fmt.Println(time.Date(2016, time.Month(m), 1, 0, 0, 0, 0, time.UTC)) } 

You converted it to an int type, but the second parameter time.Date() is of type time.Month , so it will give you an error that you are not using the correct type.

+10
source

In the first example, you declare the type as time.Month , it is not int, it is time.Month . In the second example, the type is int. If you did the cast, as in this example, it would work as you expect; https://play.golang.org/p/drD_7KiJu4

If in the first example you declared m as int or just used the operator := (the implied type would be int), and you get the same error as in the second example. Demonstrated here; https://play.golang.org/p/iWc-2Mpsly

+1
source

The Go compiler only puts constants in types on its own. Variables must be explicitly displayed.

0
source

All Articles