Commit 6c7978fc authored by Sebastien Binet's avatar Sebastien Binet Committed by Brad Fitzpatrick

reflect: add example for StructOf

This CL adds a simple example for StructOf.
The example shows how StructOf can be used in a JSON roundtrip.

Change-Id: I9ff1ea9cb8c0cf297c5fae74e68b89931076adfd
Reviewed-on: https://go-review.googlesource.com/33953
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: default avatarDavid Crawshaw <crawshaw@golang.org>
parent f251708a
......@@ -5,6 +5,8 @@
package reflect_test
import (
"bytes"
"encoding/json"
"fmt"
"io"
"os"
......@@ -107,3 +109,42 @@ func ExampleTypeOf() {
// Output:
// true
}
func ExampleStructOf() {
typ := reflect.StructOf([]reflect.StructField{
{
Name: "Height",
Type: reflect.TypeOf(float64(0)),
Tag: `json:"height"`,
},
{
Name: "Age",
Type: reflect.TypeOf(int(0)),
Tag: `json:"age"`,
},
})
v := reflect.New(typ).Elem()
v.Field(0).SetFloat(0.4)
v.Field(1).SetInt(2)
s := v.Addr().Interface()
w := new(bytes.Buffer)
if err := json.NewEncoder(w).Encode(s); err != nil {
panic(err)
}
fmt.Printf("value: %+v\n", s)
fmt.Printf("json: %s", w.Bytes())
r := bytes.NewReader([]byte(`{"height":1.5,"age":10}`))
if err := json.NewDecoder(r).Decode(s); err != nil {
panic(err)
}
fmt.Printf("value: %+v\n", s)
// Output:
// value: &{Height:0.4 Age:2}
// json: {"height":0.4,"age":2}
// value: &{Height:1.5 Age:10}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment