0
package main

import (
    "fmt"
    "os"
    "strings"
)

func main() {
    arguments := os.Args

    words := strings.Split(arguments[1], "\n")

    fmt.Println(words)
    fmt.Println(words[0])
}

example:

go run main.go "hello\nthere"

output:

[hello\nthere]
hello\nthere

expected:

[hello there]
hello

why does the separator for the newline "\n" needs to be escaped "\\n" to get the expected result?

Because you don't need to escape the newline if used like this https://play.golang.org/p/UlRISkVa8_t

Nik
  • 139
  • 2
  • 14
  • 6
    `\n` and other backslash escapes have no special meaning in the shell, so splitting them by linebreaks makes no sense – ThiefMaster Oct 22 '21 at 22:37
  • 1
    You are comparing shell syntax to Go syntax. There is no reason to assume they use the same rules for double quoted string literals. They are different languages with different design goals. – Peter Oct 23 '21 at 07:12
  • @Peter It is still not clear because once GO accesses the command line argument - its type is still a string but behaves differently.. https://i.imgur.com/hAOuZEw.png – Nik Oct 23 '21 at 07:37
  • 1
    Escape sequences are evaluated at compile time, not runtime. The Go compiler replaces the byte sequence 0x5C 0x6E (\ and n) in double quoted string literals with the single byte 0x0A. There is no backslash at runtime. – Peter Oct 23 '21 at 07:47

2 Answers2

0

You could try to pass a ANSI C like string

go run main.go $'hello\nthere'
emptyhua
  • 6,634
  • 10
  • 11
0

You're assuming that Go sees your input as:

"hello\nthere"

but it really sees your input as:

`hello\nthere`

So, if you want that input to be recognized as a newline, then you need to unquote it. But that's a problem, because it doesn't have quotes either. So you need to add quotes, then remove them before you can continue with your program:

package main

import (
   "fmt"
   "strconv"
)

func unquote(s string) (string, error) {
   return strconv.Unquote(`"` + s + `"`)
}

func main() {
   s, err := unquote(`hello\nthere`)
   if err != nil {
      panic(err)
   }
   fmt.Println(s)
}

Result:

hello
there
halfer
  • 19,824
  • 17
  • 99
  • 186
Zombo
  • 1
  • 62
  • 391
  • 407