英文:
Use int as month when constructing date
问题
当我将一个int
作为time.Date
的month
参数传递时,它可以正常工作(示例):
time.Date(2016, 1, 1, 0, 0, 0, 0, time.UTC)
但是,为什么当我尝试将一个string
转换为int
,然后使用该变量时,会出现以下错误:
cannot use mStr (type int) as type time.Month in argument to time.Date
示例:https://play.golang.org/p/-XFNZHK476
英文:
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:
<!-- language: lang-none -->
cannot use mStr (type int) as type time.Month in argument to time.Date
Example: https://play.golang.org/p/-XFNZHK476
答案1
得分: 24
你需要将值转换为正确的类型:
import (
"fmt"
"time"
"strconv"
)
func main() {
var m, _ = strconv.Atoi("01")
// 现在将 m 转换为 time.Month 类型
fmt.Println(time.Date(2016, time.Month(m), 1, 0, 0, 0, 0, time.UTC))
}
你将其转换为了 int
类型,但是 time.Date()
的第二个参数是 time.Month
类型,所以它会给你一个错误,提示你没有使用正确的类型。
英文:
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.
答案2
得分: 1
在第一个示例中,您将类型声明为time.Month
,它不是int类型,而是time.Month
类型。在第二个示例中,类型是int。如果您进行了类型转换,就像在这个示例中一样,它将按您的预期工作;https://play.golang.org/p/drD_7KiJu4
如果在您的第一个示例中,您将m
声明为int
类型,或者只是使用:=
运算符(隐含类型为int),您将得到与第二个示例中相同的错误。在这里演示;https://play.golang.org/p/iWc-2Mpsly
英文:
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
答案3
得分: 1
Go编译器只会自动将常量转换为相应的类型,变量需要显式进行类型转换。
英文:
The Go compiler only casts constants to types on its own. Variables need to be explicitly cast.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论