Reputation: 2119
After reading the laws of reflection about 10 times the last 2 months. Developing with it for the same amount of time, i have to say it is a cool and understandable language... at least to an certain level.
My background as PHP & Javascript developer are giving me an hard time to comprehend the following example:
package main
import(
"fmt"
"reflect"
)
func test1(){
type template struct {
Title string
Body string
}
data := []template{
{ Title : "About page", Body : "Body info"},
{ Body : "About page 2 ", Title : "Body info 2"},
}
fmt.Println( "-- TEST ONE --" )
fmt.Println( data[0].Title )
}
func test2(){
data := []struct{
Title string
Body string
}{
// Assign with the actual order
{ "About page", "Body info"},
// Key => Val assignment (Pretty cool)
{ Body : "Body info 2 ", Title : "About page 2"},
}
fmt.Println( "-- TEST TWO --" )
fmt.Println( data[1].Title )
}
func test3(){
type template struct {
Title string
Body string
}
Amap := map[string]interface{}{
"template" : template{},
}
w := reflect.ValueOf(Amap["template"])
x := w.Type()
y := reflect.TypeOf(w.Interface())
z := reflect.TypeOf(Amap["template"])
fmt.Printf("%+v\n", x) // main.template
fmt.Printf("%+v\n", y) // main.template
fmt.Printf("%+v\n", z) // main.template
/*
var data = struct{
// none of the above can be place in here.... ( (w|x|y|z) is not a type)
}{ "About page", "Body info"}
*/
ww := reflect.New(z)
xx := ww.Interface()
tt := reflect.TypeOf(xx)
/*
// none of the above can be used this way....
var data = ww{
}{ "About page", "Body info"}
*/
fmt.Println( "-- TEST THREE --" )
fmt.Println( data.Title )
}
func main(){
test1()
test2()
test3()
}
The above example test1()
and test2()
work as expected. I wanted to push it even further with test3()
but without success. The only way i could think of making it work was with an type switch..
But since I am trying things out I'd like to know if :
test3()
Upvotes: 2
Views: 2125
Reputation: 24878
- Is there a way to cast 1 an anonymous struct from an reflection value without type checking [2] the actual struct that is being reflected?
- Could you show me a working solution to either one of the 2 commented out code blocks from test3()
That's simple, just write:
var data = struct{string, string}{"About page", "Body info"}
If you mean to build/create/assemble a struct type on runtime I'll have to disappoint you; that's not possible.
Edit (11. Feb 2015): building struct types (as well as arrays, funcs and interfaces) on runtime by means of reflection is being implemented.
Upvotes: 3