Special Character Sequences in Go

Topic Overview and Actualization

Hello everyone! Today's journey will explore Special Character Sequences in Go. We'll delve into widely-used escape sequences – like newline or tab.

Introduction to Special Character Sequences

In Go, escape sequences are characters prefixed with a backslash (\), each having a unique behavior. They're convenient for creating line breaks, inserting tab spaces, or including a backslash or quotes in a string.

Here's an example of the newline character (\n) in use:

package main

import "fmt"

func main() {
    fmt.Println("Programming is fun!\nLet's learn Go together.")
}
// Output:
// Programming is fun!
// Let's learn Go together.

The output appears on two distinct lines!

Understanding Newline Character

The \n serves as your in-code line breaker, allowing you to split the output efficiently and improve readability. Observe it at work:

package main

import "fmt"

func main() {
    fmt.Println("Go\nProgramming")
    // Output:
    // Go
    // Programming
}

As you can see, "Go" and "Programming" are neatly broken into separate lines, all thanks to \n.

Exploring Tab and Backslash Characters

In Go, \t is used to insert a tab space. This is handy for aligning output or creating gaps in your text.

Take a look at this illustration:

package main

import "fmt"

func main() {
    fmt.Println("Go\tProgramming")
    // Output: Go     Programming (with a tab space in between)
}

To include a backslash in your string, use \\.

package main

import "fmt"

func main() {
    fmt.Println("Go\\Programming")
    // Output: Go\Programming
}

Note that there's a backslash in the output because we used \\. A single backslash inside the string is not permitted and would result in a compilation error, as the backslash is seen as a special character.

Working with Quotes in Strings

Do you want to include quotes inside a string? Go enables this with \" for double quotes. Take a look below:

package main

import "fmt"

func main() {
    fmt.Println("Go \"Programming\" is fun")
    fmt.Println("It's okay to say \"Go is cool!\"")
    // Output:
    // Go "Programming" is fun
    // It's okay to say "Go is cool!"
}

The output demonstrates how \" can seamlessly introduce quotes into strings! Note that we don't need to use \ for a single quote. ' is not a special character!

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal