Search code examples
gocode-generationgo-jennifer

How to add some lines variable number of times in a function?


I'm using Jennifer which is a code generator for Go. I want to write code to generate the main function such that some lines could be count number of times, where count is a variable I read from a file.

I tried creating the required string using for loop and passing it in the arguments, but the Block() only accepts type Code.

functoret := jen.Func().Id("main").Params().Block(
jen.Id("a").Op(":=").Id("b")
jen.Id("a").Op(":=").Id("c")
jen.Id("a").Op(":=").Id("d") //count number of times
)

Solution

  • Block accepts a slice of code fragments, so build the slice first and then call Block:

    code := []jen.Code{
        jen.Id("a").Op(":=").Id("b"),
        jen.Id("a").Op(":=").Id("c"),
    }
    for i := 0; i < count; i++ {
        code = append(code, jen.Id("a").Op(":=").Id("d"))
    }
    
    functoret := jen.Func().Id("main").Params().Block(code...)
    

    Alternatively, use the BlockFunc and Group.Add methods:

    functoret := jen.Func().Id("main").Params().BlockFunc(func(g *jen.Group) {
        g.Add(jen.Id("a").Op(":=").Id("b"))
        g.Add(jen.Id("a").Op(":=").Id("c"))
    
        for i := 0; i < count; i++ {
            g.Add(jen.Id("a").Op(":=").Id("d"))
        }
    })