Skip to content

Commit

Permalink
add top-level "go value with schema" example
Browse files Browse the repository at this point in the history
The bindnode package has its own examples,
but it can be hard to discover that it exists and what it's for.
Hopefully this top-level package example serves as a good pointer.
  • Loading branch information
mvdan authored and warpfork committed Mar 6, 2022
1 parent c6f8188 commit c10d43b
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/ipld/go-ipld-prime"
"github.com/ipld/go-ipld-prime/codec/dagjson"
"github.com/ipld/go-ipld-prime/node/basicnode"
"github.com/ipld/go-ipld-prime/node/bindnode"
"github.com/ipld/go-ipld-prime/schema"
)

Expand Down Expand Up @@ -73,3 +74,36 @@ func ExampleLoadSchema() {
// field name="foo" nullable=false type=Int
// field name="bar" nullable=true type=String
}

// Example_goValueWithSchema shows how to combine a Go value with an IPLD
// schema, which can then be used as an IPLD node.
//
// For more examples and documentation, see the node/bindnode package.
func Example_goValueWithSchema() {
type Person struct {
Name string
Age int
Friends []string
}

ts, err := ipld.LoadSchemaBytes([]byte(`
type Person struct {
name String
age Int
friends [String]
} representation tuple
`))
if err != nil {
panic(err)
}
schemaType := ts.TypeByName("Person")
person := &Person{Name: "Alice", Age: 34, Friends: []string{"Bob"}}
node := bindnode.Wrap(person, schemaType)

fmt.Printf("%#v\n", person)
dagjson.Encode(node.Representation(), os.Stdout)

// Output:
// &ipld_test.Person{Name:"Alice", Age:34, Friends:[]string{"Bob"}}
// ["Alice",34,["Bob"]]
}

0 comments on commit c10d43b

Please sign in to comment.