2016-11-02 3 views
3

Ich möchte die Ausgabevariable überprüfen ist [Zeichenfolge] Zeichenfolge oder nicht. Die Ausgabe sollte eine map [string] string sein und es sollte ein ptr sein.So überprüfen Sie die Schnittstelle ist eine Zuordnung [Zeichenfolge] Zeichenfolge in Golang

Ich überprüft ptr Wert. Aber ich weiß nicht, wie man den Schlüssel der Karte überprüft, wenn String oder nicht ist.

sorry für mein schlechtes Englisch

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

mit [Schalter] (https://golang.org/ref/spec#Type_switches) oder [type Behauptung] (https://golang.org/ref/spec#Type_assertions). Sehen Sie diese mögliche doppelte Frage + Antwort: [Wie überprüft man, ob die Schnittstelle {} eine Scheibe ist] (http://stackoverflow.com/questions/40343471/how-to-check-if-interface-is-a-slice) – icza

+0

sicher. Also ich weiß es ist eine Karte! Wie überprüfe ich die map [string] string oder map [string] int und etc ... – ahmdrz

Antwort

9

Sie müssen nicht verwenden, beziehen sich überhaupt dafür. Eine einfache Art Assert wird ausreichen;

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 
Verwandte Themen