1 回答

TA貢獻1851條經(jīng)驗 獲得超5個贊
您可以將 as 用作interface{}映射的值,它將存儲您傳遞的任何類型的值,然后使用類型斷言來獲取基礎(chǔ)值。
package main
import (
"fmt"
)
func main() {
myMap := make(map[string]interface{})
myMap["key"] = 0.25
myMap["key2"] = "some string"
fmt.Printf("%+v\n", myMap)
// fetch value using type assertion
fmt.Println(myMap["key"].(float64))
fetchValue(myMap)
}
func fetchValue(myMap map[string]interface{}){
for _, value := range myMap{
switch v := value.(type) {
case string:
fmt.Println("the value is string =", value.(string))
case float64:
fmt.Println("the value is float64 =", value.(float64))
case interface{}:
fmt.Println(v)
default:
fmt.Println("unknown")
}
}
}
游樂場上的工作代碼
接口類型的變量也有一個獨特的動態(tài)類型,它是在運行時分配給變量的值的具體類型(除非該值是預(yù)先聲明的標識符 nil,它沒有類型)。動態(tài)類型在執(zhí)行期間可能會發(fā)生變化,但存儲在接口變量中的值始終可分配給變量的靜態(tài)類型。
var x interface{} // x is nil and has static type interface{}
var v *T // v has value nil, static type *T
x = 42 // x has value 42 and dynamic type int
x = v // x has value (*T)(nil) and dynamic type *T
如果您不使用 switch 類型來獲取值,則為:
func question(anything interface{}) {
switch v := anything.(type) {
case string:
fmt.Println(v)
case int32, int64:
fmt.Println(v)
case SomeCustomType:
fmt.Println(v)
default:
fmt.Println("unknown")
}
}
您可以在開關(guān)盒中添加任意數(shù)量的類型以獲取值
- 1 回答
- 0 關(guān)注
- 116 瀏覽
添加回答
舉報