structure: improve examples

This commit is contained in:
Fatih Arslan 2014-08-11 04:15:58 +03:00
parent 1c91005c39
commit d06e3eb5fe
2 changed files with 70 additions and 13 deletions

View File

@ -48,6 +48,10 @@ m := s.Map()
// => ["gopher", 123456, true]
v := s.Values()
// Convert the values of a struct to a []*Field
// (see "Field methods" for more info about fields)
f := s.Fields()
// Check if any field of a struct is initialized or not.
if s.HasZero() {
fmt.Println("s has a zero value field")
@ -67,19 +71,13 @@ Most of the struct methods are available as global functions without the need
for a `New()` constructor:
```go
m := structure.Map(s)
v := structure.Values(s)
f := structure.Fields(s)
n := structure.Name(s)
hasZero := structure.HasZero(s)
isZero := structure.IsZero(s)
// Check if it's a struct or a pointer to struct
if structure.IsStruct(s) {
fmt.Println("s is a struct")
}
m := structure.Map(s) // Get a map[string]interface{}
v := structure.Values(s) // Get a []interface{}
f := structure.Fields(s) // Get a []*Field
n := structure.Name(s) // Get the struct name
h := structure.HasZero(s) // Check if any field is initialized
z := structure.IsZero(s) // Check if all fields are initialized
i := structure.IsStruct(s) // Check if s is a struct or a pointer to struct
```
### Field methods

View File

@ -5,6 +5,31 @@ import (
"time"
)
func ExampleNew() {
type Server struct {
Name string
ID int32
Enabled bool
}
server := &Server{
Name: "Arslan",
ID: 123456,
Enabled: true,
}
s := New(server)
fmt.Printf("Name : %v\n", s.Name())
fmt.Printf("Values : %v\n", s.Values())
fmt.Printf("Value of ID : %v\n", s.Field("ID").Value())
// Output:
// Name : Server
// Values : [Arslan 123456 true]
// Value of ID : 123456
}
func ExampleMap() {
type Server struct {
Name string
@ -191,6 +216,40 @@ func ExampleFields_nested() {
// Access.Person.Name: fatih
}
func ExampleField() {
type Person struct {
Name string
Number int
}
type Access struct {
Person Person
HasPermission bool
LastAccessed time.Time
}
access := &Access{
Person: Person{Name: "fatih", Number: 1234567},
LastAccessed: time.Now(),
HasPermission: true,
}
// Create a new Struct type
s := New(access)
// Get the Field type for "Person" field
p := s.Field("Person")
// Get the underlying "Name field" and print the value of it
name := p.Field("Name")
fmt.Printf("Value of Person.Access.Name: %+v\n", name.Value())
// Output:
// Value of Person.Access.Name: fatih
}
func ExampleIsZero() {
type Server struct {
Name string