我正在使用將fmt.Sscan字符串轉換為任何類型,這就是我正在做的事情:package mainimport ( "fmt" "reflect")func test() interface{} { return 0}func main() { a := test() // this could be any type v := "10" // this could be anything fmt.Println(reflect.TypeOf(a), reflect.TypeOf(&a)) _, err := fmt.Sscan(v, &a) fmt.Println(err)}此代碼失敗,因為Sscan不接受接口作為第二個值:can't scan type: *interface {}。演示我覺得最奇怪的是第一個 print 打?。篿nt *interface {}, is it a int or an interface?我如何斷言a正確的類型(它可以是任何原始類型)?有沒有不包含巨型 switch 語句的解決方案?謝謝。
1 回答

慕斯709654
TA貢獻1840條經驗 獲得超5個贊
以下是將字符串轉換為包支持的任何類型的值的方法fmt:
// convert converts s to the type of argument t and returns a value of that type.
func convert(s string, t interface{}) (interface{}, error) {
// Create pointer to value of the target type
v := reflect.New(reflect.TypeOf(t))
// Scan to the value by passing the pointer SScan
_, err := fmt.Sscan(s, v.Interface())
// Dereference the pointer and return the value.
return v.Elem().Interface(), err
}
像這樣稱呼它:
a := test()
a, err := convert("10", a)
fmt.Println(a, err)
- 1 回答
- 0 關注
- 127 瀏覽
添加回答
舉報
0/150
提交
取消