Skip to content

Commit

Permalink
ValuesFunc example
Browse files Browse the repository at this point in the history
  • Loading branch information
dave committed Apr 26, 2017
1 parent 1390181 commit 04b07ad
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 4 deletions.
18 changes: 16 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -656,18 +656,32 @@ fmt.Printf("%#v", c)
All constructs that accept a variadic list of items are paired with GroupFunc
functions that accept a func(*Group). Use for embedding logic.

```go
c := Id("numbers").Op(":=").Index().Int().ValuesFunc(func(g *Group) {
for i := 0; i <= 5; i++ {
g.Lit(i)
}
})
fmt.Printf("%#v", c)
// Output:
// numbers := []int{0, 1, 2, 3, 4, 5}
```

```go
increment := true
name := "a"
c := Func().Id("a").Params().BlockFunc(func(g *Group) {
g.Id(name).Op("=").Lit(1)
if increment {
g.Id("a").Op("++")
g.Id(name).Op("++")
} else {
g.Id("a").Op("--")
g.Id(name).Op("--")
}
})
fmt.Printf("%#v", c)
// Output:
// func a() {
// a = 1
// a++
// }
```
Expand Down
2 changes: 2 additions & 0 deletions README.md.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,8 @@ render rune and byte literals.
All constructs that accept a variadic list of items are paired with GroupFunc
functions that accept a func(*Group). Use for embedding logic.

{{ "ExampleValuesFunc" | example }}

{{ "ExampleBlockFunc" | example }}

### Add
Expand Down
18 changes: 16 additions & 2 deletions jen/examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -304,18 +304,32 @@ func ExampleBlock_if() {
// }
}

func ExampleValuesFunc() {
c := Id("numbers").Op(":=").Index().Int().ValuesFunc(func(g *Group) {
for i := 0; i <= 5; i++ {
g.Lit(i)
}
})
fmt.Printf("%#v", c)
// Output:
// numbers := []int{0, 1, 2, 3, 4, 5}
}

func ExampleBlockFunc() {
increment := true
name := "a"
c := Func().Id("a").Params().BlockFunc(func(g *Group) {
g.Id(name).Op("=").Lit(1)
if increment {
g.Id("a").Op("++")
g.Id(name).Op("++")
} else {
g.Id("a").Op("--")
g.Id(name).Op("--")
}
})
fmt.Printf("%#v", c)
// Output:
// func a() {
// a = 1
// a++
// }
}
Expand Down

0 comments on commit 04b07ad

Please sign in to comment.