When I supply an 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 a string
to int
and then use that variable, I get the error:
cannot use mStr (type int) as type time.Month in argument to time.Date
Example: https://play.golang.org/p/-XFNZHK476
You have to convert the value to the proper 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 a type int
, but the 2nd parameter of time.Date()
is of type time.Month
so it would give you an error that you are not using the correct type.
In the first example you're declaring the type as a time.Month
, it is not an int, it is a time.Month
. In the second example the type is an int. If you were to do a cast, like in this example it would work as you expect; https://play.golang.org/p/drD_7KiJu4
If in your first example you declared m
as an int
or just used the :=
operator (the implied type would be int) and you would get the same error as in the second example. Demonstrated here; https://play.golang.org/p/iWc-2Mpsly
The Go compiler only casts constants to types on its own. Variables need to be explicitly cast.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With