Hello everyone! Today's journey will explore Special Character Sequences in Go. We'll delve into widely-used escape sequences – like newline or tab.
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:
Go1package main 2 3import "fmt" 4 5func main() { 6 fmt.Println("Programming is fun!\nLet's learn Go together.") 7} 8// Output: 9// Programming is fun! 10// Let's learn Go together.
The output appears on two distinct lines!
The \n
serves as your in-code line breaker, allowing you to split the output efficiently and improve readability. Observe it at work:
Go1package main 2 3import "fmt" 4 5func main() { 6 fmt.Println("Go\nProgramming") 7 // Output: 8 // Go 9 // Programming 10}
As you can see, "Go" and "Programming" are neatly broken into separate lines, all thanks to \n
.
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:
Go1package main 2 3import "fmt" 4 5func main() { 6 fmt.Println("Go\tProgramming") 7 // Output: Go Programming (with a tab space in between) 8}
To include a backslash in your string, use \\
.
Go1package main 2 3import "fmt" 4 5func main() { 6 fmt.Println("Go\\Programming") 7 // Output: Go\Programming 8}
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.
Do you want to include quotes inside a string? Go enables this with \"
for double quotes. Take a look below:
Go1package main 2 3import "fmt" 4 5func main() { 6 fmt.Println("Go \"Programming\" is fun") 7 fmt.Println("It's okay to say \"Go is cool!\"") 8 // Output: 9 // Go "Programming" is fun 10 // It's okay to say "Go is cool!" 11}
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!
Great job! You've now mastered the special character sequences in Go — newline (\n
), tab (\t
), backslash (\\
), and quotes (\"
). With these in your arsenal, you're equipped to handle many string manipulation tasks in real-world programming scenarios. Practice exercises are up next. Apply what you've learned to reinforce your understanding. Keep practicing and enjoy programming!