Skip to content

Commit

Permalink
Merge pull request #10 from HotelUrbano/feature/fill-structs
Browse files Browse the repository at this point in the history
Feature/fill structs
  • Loading branch information
bernardolm authored Apr 25, 2018
2 parents 744b703 + 7388a78 commit 0c79ea3
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 1 deletion.
8 changes: 7 additions & 1 deletion Gopkg.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions Gopkg.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@
name = "gopkg.in/h2non/gock.v1"
version = "1.0.8"

[[constraint]]
branch = "master"
name = "github.com/fatih/structs"

[prune]
go-tests = true
unused-packages = true
14 changes: 14 additions & 0 deletions lib/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import (
"strconv"
"strings"
"time"

"github.com/fatih/structs"
)

const (
Expand Down Expand Up @@ -451,3 +453,15 @@ func Truncate(s string, i int) (r string) {
r = strings.Replace(r, " ", "", -1)
return
}

// Fill merges data from struct instance to another
// By @titpetric suggested in https://scene-si.org/2016/06/01/golang-tips-and-tricks
func Fill(dest interface{}, src interface{}) {
mSrc := structs.Map(src)
mDest := structs.Map(dest)
for key, val := range mSrc {
if _, ok := mDest[key]; ok {
structs.New(dest).Field(key).Set(val)
}
}
}
19 changes: 19 additions & 0 deletions lib/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -642,3 +642,22 @@ func TestTruncate(t *testing.T) {
}`
assert.Equal(t, expected, Truncate(json1, len(json1)))
}

func TestFill(t *testing.T) {
a := struct {
ID int
Name string
IsAdmin bool
}{}

b := struct {
Name string
}{}

b.Name = "Bobby"

Fill(&a, b)

assert.Equal(t, "Bobby", a.Name)
}

0 comments on commit 0c79ea3

Please sign in to comment.