Skip to content

Commit

Permalink
add set to readme
Browse files Browse the repository at this point in the history
  • Loading branch information
youyuanwu committed Aug 8, 2020
1 parent 4dcbf27 commit a54d1f1
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
31 changes: 31 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,37 @@ Retrieves the value of the pointer or default.
GetOrElse(str, "foobar") // string{"hello world"}
GetOrElse(nil, "foobar") // string{"foobar"}
funk.Set
........
Set value at a path of a struct

.. code-block:: go
var bar Bar = Bar{
Name: "level-0",
Bar: &Bar{
Name: "level-1",
Bars: []*Bar{
{Name: "level2-1"},
{Name: "level2-2"},
},
},
}
_ = Set(&bar, "level-0-new", "Name")
fmt.Println(bar.Name) // "level-0-new"
MustSet(&bar, "level-1-new", "Bar.Name")
fmt.Println(bar.Bar.Name) // "level-1-new"
Set(&bar, "level-2-new", "Bar.Bars.Name")
fmt.Println(bar.Bar.Bars[0].Name) // "level-2-new"
fmt.Println(bar.Bar.Bars[1].Name) // "level-2-new"
funk.MustSet
............
Short hand for funk.Set if struct does not contain interface{} field type to discard errors.


funk.Keys
.........
Expand Down
33 changes: 33 additions & 0 deletions assign_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -449,3 +449,36 @@ func TestMustSet_Basic(t *testing.T) {
is.Equal("b", s.Name)
})
}

// Examples

func ExampleSet() {

var bar Bar = Bar{
Name: "level-0",
Bar: &Bar{
Name: "level-1",
Bars: []*Bar{
{Name: "level2-1"},
{Name: "level2-2"},
},
},
}

_ = Set(&bar, "level-0-new", "Name")
fmt.Println(bar.Name)

// discard error use MustSet
MustSet(&bar, "level-1-new", "Bar.Name")
fmt.Println(bar.Bar.Name)

_ = Set(&bar, "level-2-new", "Bar.Bars.Name")
fmt.Println(bar.Bar.Bars[0].Name)
fmt.Println(bar.Bar.Bars[1].Name)

// Output:
// level-0-new
// level-1-new
// level-2-new
// level-2-new
}

0 comments on commit a54d1f1

Please sign in to comment.