1

I'm trying to write a .xml file in golang and when I try to write to a newline and use \n, it literally prints \n as part of the string.

How can I force a new line to be printed in the file?

Here is what my code looks like so far:

fmt.Fprint(file, "<card>\n")
fmt.Fprintf(file, `<title>title</title>\n`)

and that is printing <card>\n<title>title</title>\n

wordSmith
  • 2,993
  • 8
  • 29
  • 50

1 Answers1

2

Actually, it's printing

<card>
<title>title</title>\n

As you can see here.

The reason is that backslashes are not interpolated in raw strings, i.e. strings that are enclosed with `. If you replace your second line with

fmt.Fprintf("<title>title</title>\n")

your program should work as intended.

publysher
  • 11,214
  • 1
  • 23
  • 28
  • Ah, okay. That's right! However, why am I getting these 2 errors now saying that the string is unexpected? Here is the code in the go playground: http://play.golang.org/p/DvW5NS7S9O – wordSmith Oct 14 '14 at 22:05
  • @CharlieTumahai one more thing. Now these errors are coming. It is saying there is a semi-colon or new line before the else, but I don't see one anywhere. Here is the code: http://play.golang.org/p/yELWfIdWz5 – wordSmith Oct 14 '14 at 22:26
  • @user3743069 That's because the compiler will put semi colons in there for you based on certain rules documented here: https://golang.org/doc/effective_go.html#semicolons. In your specific case, its because you have the `else if` on the line after the `if`'s closing brace. It must be on the same line. – Simon Whitehead Oct 15 '14 at 00:11