Home > other >  Why Go split by newline separator needs to be escaped when received as an argument
Why Go split by newline separator needs to be escaped when received as an argument

Time:10-24

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

CodePudding user response:

You could try to pass a ANSI C like string

go run main.go $'hello\nthere'

CodePudding user response:

Youre 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 thats a problem, because it doesnt 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
  •  Tags:  
  • go
  • Related