Raw and Interpreted Strings

I was just about to post a reply and see that Jakob has already replied with something similar to what I was going to suggest.

Basically, if you think about it, if you wanted to convert a literal \n to a newline in a string such as \nhello, how do you know if the \n is a newline or if the string is actually a \ followed by nhello, so in this regard, I don’t personally know any simple way how you could switch back and forth correctly.

With this in mind, you could always use something like the following if you know for certain that there will not be mix ups in your string and know that anytime there is something such as \nhello, that you actually want a newline character and not a \ and then some text.

package main

import (
	"fmt"
	"log"
	"strconv"
	"strings"
)

func main() {
	str := `Hello\nWorld!`
	str = strconv.Quote(str)
	replaced := strings.Replace(str, `\\`, "\\", -1)
	newstr, err := strconv.Unquote(replaced)
	if err != nil {
		log.Fatalln(err)
	}
	fmt.Println(newstr)
}