Golang Escape Backslash [100% Working]

In this article, I will show you how to escape Backslash in Golang. A backslash (\) is used as an escape sequence character in most programming languages, and Golang is no exception. Thus, if a user needs to insert a backslash into a string, he can use either of the two commonly used methods: type the backslash twice and raw string literals. If we want to remove the backslash from a string, we can replace them with empty characters.

 

Method-1: Escape single and double backslash in GO using backslash (\)

To print out the backslash, we can use another backslash just before the backslash (\) we want to display. Go interpreter treats it as a single backslash character instead of an escape sequence character.

Advertisement
package main

import "fmt"

func main() {
	// using another backslash
	fmt.Println("\\Welcome to GoLinuxCloud\\")

	fmt.Println("Which is better: Golang \\\\ Java?")
}

Output:

\Welcome to GoLinuxCloud\
Which is better: Golang \\ Java?

Note that:

  • We can insert the backslash at any desired position in the string.
  • If the number of backslash is an odd number, the program will crash.

 

Method-2: Escape backslash by using Raw String Literals

A string literal represents a string constant obtained from concatenating a sequence of characters. There are two forms: raw string literals and interpreted string literals.

We have an article about "How to PROPERLY write multiline strings in GO?". The ideal is the same, we can use a raw string lateral ` to write a backslash in the string. Consider the below example to understand how to insert one or multiple backlashes to a string:

package main

import "fmt"

func main() {
	// using string literals
	fmt.Println(`\GoLinux\Cloud\`)
	fmt.Println(`GoLinux\\Cloud`)
	fmt.Println(`GoLinux\\\Cloud`)
}

Output:

\GoLinux\Cloud\
GoLinux\\Cloud
GoLinux\\\Cloud

 

Summary

In this tutorial we learned how to escape backslash in golang programming language. The logic is pretty much same which applies to any other escape character. We also use backslash to escape a character so the same can be used to escape backslash itself. You just have to make sure that number of backslash used is in even numbers or else your code will crash with error like syntax error: unexpected newline in argument list; possibly missing comma or )

 

Categories GO

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X