英文:
Get switch type case to int64 - Golang
问题
如何将空接口转换为int64类型?
var vari interface{}
vari = 7466
switch v := vari.(type) {
case int64:
fmt.Println("integer", v)
default:
fmt.Println("unknown")
}
这段代码会打印出"unknown"。
如果我将其用于int类型,它可以正常工作(打印"integer 7466"),但对于int64类型却不行。我该如何获取int64类型的结果?
英文:
how can i get type switching for an empty interface to an int64
var vari interface{}
vari = 7466
switch v := vari.(type) {
case int64:
fmt.Println("integer", v)
default:
fmt.Println("unknown")
}
This prints unknown.
It works fine (prints "integer 7466") if i do it for int but not for int64. How can i get int64?
答案1
得分: 4
字面值7466
是一个无类型常量,在这个上下文中,它被解释为int
而不是int64
。所以要么将情况测试为int
,要么这样做:
vari = int64(7466)
这是因为int
和int64
是不同的类型。
英文:
The literal 7466
is an untyped constant, and in that context, it is interpreted as an int
, not as an int64
. So either test the case for int
, or do:
vari = int64(7466)
This is because int
and int64
are distinct types.
答案2
得分: 1
这里有两种情况需要考虑:
-
你绝对知道接口赋值的值具有某种已知的整数类型。例如:
var vari interface{} vari = 7466 // 可能是 int64|32|16|8(7466) v, ok := vari.(int) // 或 int64|32|16|8 if !ok { fmt.Println("未知") return 0 } return int64(v)
-
你不知道接口中的值的类型。可以使用 reflect 包来帮助你。Playground
func getInt64(v interface{}) (int64, error) { switch reflect.TypeOf(v).Kind() { case reflect.Int8: d, _ := v.(int8) return int64(d), nil case reflect.Int16: d, _ := v.(int16) return int64(d), nil case reflect.Int32: d, _ := v.(int32) return int64(d), nil case reflect.Int64: d, _ := v.(int64) return d, nil case reflect.Int: d, _ := v.(int) return int64(d), nil // ... 如果需要,处理 uint } return 0, fmt.Errorf("不是整数类型: %v", v) }
英文:
There are two cases to consider here:
-
You absolutely know that the value assigned to the interface has some known integer type. Example:
var vari interface{} vari = 7466 // could be int64|32|16|8(7466) v, ok := vari.(int) // or int64|32|16|8 if !ok { fmt.Println("unknown") return 0 } return int64(v)
-
You don't know what the type of the value in the interface is. The reflect package might help you. Playground
func getInt64(v interface{}) (int64, error) { switch reflect.TypeOf(v).Kind() { case reflect.Int8: d, _ := v.(int8) return int64(d), nil case reflect.Int16: d, _ := v.(int16) return int64(d), nil case reflect.Int32: d, _ := v.(int32) return int64(d), nil case reflect.Int64: d, _ := v.(int64) return d, nil case reflect.Int: d, _ := v.(int) return int64(d), nil // ... tackle uint if needed } return 0, fmt.Errorf("not interger: %v", v) }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论