Tuesday, December 15, 2020

Escape Sequences in Go

Want to know more about escape sequences in Go? Read to understand.

Go as other programming languages has the concept of escaping. A escaping sequence is a combination of characters that has a meaning other than the literal characters contained therein. An escaping sequence commonly uses a escape character which in Go is the \ character. Let's understand more about escaping in Go's context.

Why escape?

Escaping is a commonly used technique that developers use resort to escaping code to:

  • encode commands or special data which cannot be directly represented by the alphabet.
  • represent characters which cannot be typed in the current context, or would have an undesired interpretation

Escaping in Go

As other programming languages, Go utilizes the backslash (\) character to escape. What to use next? Depends on what you need. Here are some useful values to get you started:

Escape Sequence Value
\\ the \ character
\' the ' character
\" the " character
\? the ? character
\a an alert
\b backspace
\f form feed
\n a new line
\r carriage return
\t an horizontal tab
\xFF hexadecimal "FF"

Examples

So let's check some examples:

package main

import (
"fmt"
)

func main() {
dec := 22
octal := 033
hex := 0xFF
fmt.Printf("Decimal %v, Hex: %v, Octal: %v\n", dec, hex, octal)
fmt.Println("Some\ttab")
fmt.Println("A quote: \"")
fmt.Println("What\nabout\nline\nbreaks")
}

Decimal 22, Hex: 255, Octal: 27
Some tab
A quote: "
What
about
line
breaks

Conclusion

On this article we learned about escaping. Escaping in Go is very similar to other programming languages and is extensively used to encode commands or special data which cannot be directly represented by the alphabet or to represent characters which cannot be typed in the current context, or would have an undesired interpretation.

Reference

See Also

Any comment about this page? Please contact us on Twitter

Featured Article

Raw String Literals in Go

Learn what are Raw String Literals in Go and how to use them On a previous posts we discussed Runes, Variables and Strings in ...

Popular Posts