Signup/Sign In

String literals in Golang.

From previous articles, we know that strings in Golang are contained in between double quotes " " , but if we try to write on next line or write a multiline string. We may break the syntax or identations used in Go language. You may have tried to use Python's method ("""string"""), but that will again break Golang's syntax:

multilineString := """line 1
line 2
line 3"""

Let's dive deeper into string literals in Golang and find out different ways to write multiline strings withing Golang.

What is a String literal in Go language?

A string literal in Go language represents a string constant obtained from concatenating a sequence of characters.

There are two forms of string literals in Go language: raw string literals and interpreted string literals.

  1. Raw string literals are every character sequence included between back quotes `foo`(Keyboard location: below ESC key), where foo could be anything but should not contain a back quote. For python programmers, `foo` in Golang is the same as """foo""" in Python. The characters between back quotes will be treated as raw strings. Eg. A carriage return (\r) or line break (\n) will not be treated speacially. The value of a raw string literal is the string composed of the uninterpreted (implicitly UTF-8-encoded) characters; in particular, backslashes have no special meaning.

  2. Interpreted string literals are character sequences between double quotes, as in "bar" where the bar could be anything except new line character or a double quote. But you can use rune literals to add a double as pard of bar with a backslash as \". You can introduce characters of different encodings.

How to write multiline string in Go language?

  • Using raw string Literals - you can use multiline strings delimited by back ticks (`). (only new lines between back quotes will be considered as new line.)
    • `line 1
      line 2
          line 3
      line #$(* 4`
    • Also, special characters are not trated exceptionally,
    • package main
      
      import (
          "fmt"
      )
      
      func main(){
          multiLine := `line 1
      line 2 \n
      line 3 \n
      line 4`
      
          fmt.Print(multiline)
      }
      

    • line 1
      line 2 \n
      line 3 \n
      line 4
      Program exited.

  • Using interpreted string literals - As we know that special character delimited between double quotes are interpreted to have special meaning.
    • "line 1 \nline2 \n  line3 \nline4"

    • line 1
      line2
      line3
      line4

    • So, we use string concatenation to make it more readable.
    • package main
      
      import (
      	"fmt"
      )
      
      func main() {
      	multiline := "line 1 \n" +
      		"line2 \n" +
      		"  line3 \n" +
      		"line4"
      
      	fmt.Print(multiline)
      }
      

    • line 1
      line2
      line3
      line4

How to convert a raw string literal to interpreted string literal?

For example, printing this raw string literal gives

func main() {
    s := `\033[1mString.\033[0m`
    println(s)
}


\033[1mString.\033[0m

but we want the same result like when we use interpreted string literals.

func main() {
    s := "\033[1mString.\033[0m"
    println(s) 
}


String.

So, we need to change raw string literal to interpreted string literal. We may follow use these steps:

  • Import strconv package from Go language's standard library.
  • import (
        "fmt"
        "strconv"
    )
  • And then use strconv.Unquote() function.

The string value passed to strconv.Unquote() must contain wrapping double quotes or backticks, and since the source s does not contain the wrapping quotes. i.e, `"` + s + `"`

  • func main() {
        s := `\033[1mString in bold.\033[0m`
    
        sInterpreted, err := strconv.Unquote(`"` + s + `"`)
        if err != nil {
            panic(err)
        }
    }

Finally, We have this working script.

package main

import(
    "fmt"
    "strconv"
)

func main() {
    s := `\033[1mString in bold.\033[0m`

    sInterpreted, err := strconv.Unquote(`"` + s + `"`)
    if err != nil {
        panic(err)
    }
    fmt.Println(sInterpreted)
}


String.

Conclusion

In this tutorial, we learnt about string literals in Golang. there are two type of string literals; Raw string literal and Interpreted string literal.



About the author:
Pradeep has expertise in Linux, Go, Nginx, Apache, CyberSecurity, AppSec and various other technical areas. He has contributed to numerous publications and websites, providing his readers with insightful and informative content.