How to write backslash in Golang string?

In most of the programming languages, Backslash (\) works as an escape sequence character and the same is the case with Golang. Thus, if a user needs to write backslash in a string, he can make use of the two common methods.

1. A user can use another backslash just before the backslash (\) he/she wants to display.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Printing backslash in Golang string
package main
  
import "fmt"
  
func main() {
  
    // using another backslash
    fmt.Println("\\Hello, Welcome to GeeksforGeeks")
}

chevron_right


Output:

\Hello, Welcome to GeeksforGeeks

Explanation: Suppose, the user wants to write backslash at the starting of the string. This is done by using an escape operator “\” just before the desired backslash as shown in the above example. In this manner, the user can insert the backslash at any desired position in the string.



2. Another approach is to use a raw string literal (`).

filter_none

edit
close

play_arrow

link
brightness_4
code

// Printing backslash in Golang string
package main
  
import "fmt"
  
func main() {
  
    // using raw string lateral (`)
    fmt.Println(`\Happy Learning\`)
}

chevron_right


Output:

\Happy Learning\

Explanation: In this example, we used a raw string lateral (`) to write a backslash in the string. If a user wants to write a string in between the backslashes, he can do so by writing the desired string within raw string literals (`) as shown in this example.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.