Multiline statements in Golang

As Golang (unlike C, C++, Java, etc.) frees a programmer from using semi-colon ‘;’ to terminate a statement, one might find it problematic to write a miltiline statement in Go.

Lets start with a quote :

“Like C, Go’s formal grammar uses semicolons to terminate statements; unlike C,those semicolons do not appear in the source. Instead the lexer uses a simple rule to insert semicolons automatically as it scans, so the input text is mostly free of them. “

So, based on my experience so far, here is a trick that I would suggest, one can break a line after “an operator”.

        result := a +
                b +
func add(a int,
        b int,
        c int) (result int) {
        result = a + b + c

Now coming to strings, they can we written in two ways.

1) Interpreted string literal :

        str := "Lorem ipsum dolor sit amet, consectetur adipisicing" +
               " elit, sed do eiusmod tempor\nincididunt ut labore " +
               " et dolore magna aliqua. Ut enim ad minim veniam," +
               " quis nostrud\nexercitation ullamco laboris ..."

2) Raw string literal :
For multiline strings, back quote ‘`’ can also be used with a couple of restrictions :
a) Any character is legal except back quote.
b) Escape sequences won’t be interpreted.

        str := `Lorem ipsum dolor sit amet, consectetur adipisicing 
                elit, sed do eiusmod tempor incididunt ut labore et
                dolore magna aliqua. Ut enim ad minim veniam, quis
                nostrud exercitation ullamco laboris ...`

go go go…

Leave a Reply

Your email address will not be published. Required fields are marked *