2016-11-02 30 views
3

我想檢查輸出變量是否爲map [string]字符串。 輸出應該是一個map [string]字符串,它應該是一個ptr。如何查看界面是golang中的map [string]字符串

我檢查了ptr值。但是如果是字符串,我不知道如何檢查map的鍵。

對不起我的英文不好

import (
    "fmt" 
    "reflect" 
) 

func Decode(filename string, output interface{}) error { 
    rv := reflect.ValueOf(output) 
    if rv.Kind() != reflect.Ptr { 
     return fmt.Errorf("Output should be a pointer of a map") 
    } 
    if rv.IsNil() { 
     return fmt.Errorf("Output in NIL") 
    } 
    fmt.Println(reflect.TypeOf(output).Kind()) 
    return nil 
} 
+1

使用[式開關(https://golang.org/ref/spec#Type_switches)或[式斷言(https://golang.org/ref/spec#Type_assertions)。看看這個可能的重複問題+回答:[如何檢查interface {}是否是一個片段](http://stackoverflow.com/questions/40343471/how-to-check-if-interface-is-a-slice) – icza

+0

當然。所以我知道它的地圖!如何檢查它的地圖[字符串]字符串或地圖[字符串]詮釋等... – ahmdrz

回答

9

您不必使用反映在所有的這一點。一個簡單的類型assert就足夠了;

unboxed, ok := output.(*map[string]string) 
if !ok { 
    return fmt.Errorf("Output should be a pointer of a map") 
} 
if unboxed == nil { 
    return fmt.Errorf("Output in NIL") 
} 
// if I get here unboxed is a *map[string]string and is not nil 
相關問題