我編寫了一個(gè)函數(shù),該函數(shù)將從map [string] Foo返回排序后的字符串片段。我很好奇創(chuàng)建通用例程的最佳方法是什么,該例程可以從以字符串為鍵的映射的任何類型返回經(jīng)過排序的字符串切片。有沒有一種使用接口規(guī)范的方法?例如,有什么方法可以執(zhí)行以下操作:type MapWithStringKey interface { <some code here>}要實(shí)現(xiàn)上面的接口,一種類型將需要字符串作為鍵。然后,我可以編寫一個(gè)泛型函數(shù),該函數(shù)返回用于實(shí)現(xiàn)類型的鍵的排序列表。這是我當(dāng)前使用反射模塊的最佳解決方案:func SortedKeys(mapWithStringKey interface{}) []string { keys := []string{} typ := reflect.TypeOf(mapWithStringKey) if typ.Kind() == reflect.Map && typ.Key().Kind() == reflect.String { switch typ.Elem().Kind() { case reflect.Int: for key, _ := range mapWithStringKey.(map[string]int) { keys = append(keys, key) } case reflect.String: for key, _ := range mapWithStringKey.(map[string]string) { keys = append(keys, key) } // ... add more cases as needed default: log.Fatalf("Error: SortedKeys() does not handle %s\n", typ) } sort.Strings(keys) } else { log.Fatalln("Error: parameter to SortedKeys() not map[string]...") } return keys}單擊以獲取Go Playground版本即使在編譯時(shí),我也必須為每種受支持的類型編寫類型斷言,盡管我們應(yīng)該知道m(xù)apWithStringKey參數(shù)的確切類型。
Go是否允許為具有特定鍵類型的映射指定接口?
慕的地6264312
2021-05-13 18:27:15