为什么当作为参数接收时,Go中的按换行符分割需要进行转义?

huangapple go评论86阅读模式
英文:

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

问题

包括代码和注释在内的所有内容已经翻译如下:

package main

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

func main() {
	arguments := os.Args

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

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

示例:

go run main.go "hello\nthere"

输出:

[hello\nthere]
hello\nthere

预期输出:

[hello there]
hello

为什么换行符的分隔符 "\n" 需要转义为 "\\n" 才能得到预期的结果?

因为如果像这样使用,你不需要转义换行符:https://play.golang.org/p/UlRISkVa8_t

英文:
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

答案1

得分: 0

你可以尝试传递一个类似ANSI C的字符串

go run main.go $'hello\nthere'
英文:

You could try to pass a ANSI C like string

go run main.go $'hello\nthere'

答案2

得分: 0

你假设Go语言将你的输入视为:

"hello\nthere"

但实际上,Go语言将你的输入视为:

`hello\nthere`

所以,如果你希望该输入被识别为换行符,那么你需要取消引号。但这是一个问题,因为它也没有引号。所以你需要添加引号,然后在继续执行程序之前将其删除:

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)
}

结果:

hello
there
英文:

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

huangapple
  • 本文由 发表于 2021年10月23日 06:28:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/69683669.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定