Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
itsubaki committed Mar 6, 2021
2 parents 1449cb9 + d3aba34 commit f8a4cad
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 10 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
# gostruct
A Runtime Struct Builder for Go

Runtime Struct Builder for Go

## Example

```go
func Example() {
person := gostruct.New().
AddField("Name", reflect.TypeOf("")).
AddField("Age", reflect.TypeOf(int64(0))).
AddString("Name").
AddInt64("Age").
Build()

p := person.New()
Expand All @@ -22,4 +22,4 @@ func Example() {
// struct { Name string; Age int64 }: {Name:gopher Age:11}
// *struct { Name string; Age int64 }: &{Name:gopher Age:11}
}
```
```
16 changes: 16 additions & 0 deletions builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,22 @@ func (b *Builder) AddField(name string, ftype reflect.Type) *Builder {
return b
}

func (b *Builder) AddString(name string) *Builder {
return b.AddField(name, reflect.TypeOf(""))
}

func (b *Builder) AddBool(name string) *Builder {
return b.AddField(name, reflect.TypeOf(true))
}

func (b *Builder) AddInt64(name string) *Builder {
return b.AddField(name, reflect.TypeOf(int64(0)))
}

func (b *Builder) AddFloat64(name string) *Builder {
return b.AddField(name, reflect.TypeOf(float64(1.2)))
}

func (b *Builder) Build() Struct {
strct := reflect.StructOf(b.field)

Expand Down
11 changes: 5 additions & 6 deletions builder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,24 @@ package gostruct_test

import (
"fmt"
"reflect"

"github.com/itsubaki/gostruct"
)

func Example() {
person := gostruct.New().
AddField("Name", reflect.TypeOf("")).
AddField("Age", reflect.TypeOf(int64(0))).
AddString("Name").
AddInt64("Age").
Build()

p := person.New()
p.SetString("Name", "gopher")
p.SetInt64("Age", 8)
p.SetInt64("Age", 11)

fmt.Printf(" %T: %+v\n", p.Interface(), p.Interface())
fmt.Printf("%T: %+v\n", p.Addr(), p.Addr())

// Output:
// struct { Name string; Age int64 }: {Name:gopher Age:8}
// *struct { Name string; Age int64 }: &{Name:gopher Age:8}
// struct { Name string; Age int64 }: {Name:gopher Age:11}
// *struct { Name string; Age int64 }: &{Name:gopher Age:11}
}

0 comments on commit f8a4cad

Please sign in to comment.