2017-01-11 1 views
0

Ich habe eine neue Art von Karte abgeleitet sind, wie:erstellen dann eine Karte durch Reflexion Modifizieren

type mapp map[string]interface{} 

mit einer kleinen Funktion auf es

func (c mapp) Set() error { 
    // c is nil 
    c["a"] = "b" 
    return nil 
} 

type Setter interface { 
    Set() error 
} 

func main() { 
    var aa mapp 
    out := reflect.ValueOf(&aa) 
    s := out.Interface().(Setter) 
    s.Set() 
} 

Dieser Code auf einer Struktur funktioniert, warum Sie diesen Code scheitert, wenn es um einen Kartentyp geht?

Hier ist ein Spielplatz: https://play.golang.org/p/Z1LFqb6kF7

Vielen Dank,

Asaf.

Antwort

2

Go-Maps (und Slices) werden über make erstellt. Die entsprechende Funktion in reflect ist reflect.MakeMap

out := reflect.ValueOf(&aa).Elem() 
out.Set(reflect.MakeMap(out.Type())) 
s := out.Interface().(Setter) 
s.Set() 
+0

Dank, kann immer noch nicht, obwohl Karte Inhalt ändern? https://play.golang.org/p/wXbVdcykZf – asaf000

+0

@ asaf000: wenn Sie 'aa' modifizieren möchten, dann müssen Sie seinen Wert einstellen. 'aa' ist null, also gibt es dort nichts zu modifizieren. https://play.golang.org/p/XWcx5gDPu7 – JimB

+0

genial, danke! – asaf000

Verwandte Themen