2016-05-12 12 views
2

Ich wünschte, ich könnte meinen Typ der Struktur wiederherstellen und eine Variable dieses Typs deklarieren.Go Relflect Declare Typ struct

Ich versuchte mit Reflect, aber ich kann den Weg nicht finden.

package main 

import (
    "fmt" 
    "reflect" 
) 

type M struct { 
    Name string 
} 

func main() { 
    type S struct { 
     *M 
    } 

    s := S{} 
    st := reflect.TypeOf(s) 
    Field, _ := st.FieldByName("M") 
    Type := Field.Type 
    test := Type.Elem() 
    fmt.Print(test) 
} 

Antwort

2

Verwenden reflect.New mit Ihrer Art, hier ist ein Beispiel für Name auf eine neue Instanz von M Struktur mit Reflexion Einstellung:

package main 

import (
    "fmt" 
    "reflect" 
) 

type M struct { 
    Name string 
} 

func main() { 
    type S struct { 
     *M 
    } 

    s := S{} 
    mStruct, _ := reflect.TypeOf(s).FieldByName("M") 
    mInstance := reflect.New(mStruct.Type.Elem()) 
    nameField := mInstance.Elem().FieldByName("Name") 
    nameField.SetString("test") 
    fmt.Print(mInstance) 
} 
Verwandte Themen