![](/img/trans.png)
[英]How can I check if a posted file via multipart form is of image type and that it is less than a given maxsize in Go?
[英]Go - How can I check for type equality?
說我有以下代碼:
var x interface{}
y := 4
x = y
fmt.Println(reflect.TypeOf(x))
這將打印int作為類型。 我的問題是如何測試類型? 我知道有這樣的類型開關,所以我可以這樣做:
switch x.(type) {
case int:
fmt.Println("This is an int")
}
但如果我只想檢查一個特定的類型,那么交換機似乎是錯誤的工具。 是否有更直接的方法來做到這一點
reflect.TypeOf(x) == int
或類型開關的方式去?
類型斷言返回兩個值..第一個是轉換后的值,第二個是bool,指示類型斷言是否正常工作。
所以你可以這樣做:
_, ok := x.(int)
if ok {
fmt.Println("Its an int")
} else {
fmt.Println("Its NOT an int")
}
..或者,速記:
if _, ok := x.(int); ok {
fmt.Println("Its an int")
}
我剛剛想出了基於此的另一種方法:
if _, ok := x.(int); ok {
fmt.Println("This is an int")
}
在Effective Go中,您可以找到一個非常簡單的示例,說明您要實現的目標。
var t interface{}
t = functionOfSomeType()
switch t := t.(type) {
default:
fmt.Printf("unexpected type %T", t) // %T prints whatever type t has
case bool:
fmt.Printf("boolean %t\n", t) // t has type bool
case int:
fmt.Printf("integer %d\n", t) // t has type int
case *bool:
fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool
case *int:
fmt.Printf("pointer to integer %d\n", *t) // t has type *int
}
如果您需要檢查一種類型,請使用簡單的if ,否則請使用開關以提高可讀性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.