英文:
Cannot assign string with single quote in golang
问题
我正在学习Go语言,在处理字符串时,我注意到如果一个字符串使用单引号括起来,Golang会给我一个错误,但双引号却可以正常工作。
这是我在我的系统上得到的错误信息:
illegal rune literal
而当我在playground上尝试同样的操作时,我得到了这个错误:
prog.go:9: missing '
prog.go:9: syntax error: unexpected name, expecting semicolon or newline or }
prog.go:9: newline in string
prog.go:9: empty character literal or unescaped ' in character literal
prog.go:9: missing '
我无法理解其中的确切原因,因为在Python、Perl等语言中,可以使用单引号和双引号声明字符串。
英文:
I am learning go and when playing with string I noticed that if a string is in single quotes then golang is giving me an error but double quotes are working fine.
func main() {
var a string
a = 'hello' //will give error
a = "hello" //will not give error
}
This is the error I get on my system:
illegal rune literal
While when I try to do the same on playground I am getting this error:
prog.go:9: missing '
prog.go:9: syntax error: unexpected name, expecting semicolon or newline or }
prog.go:9: newline in string
prog.go:9: empty character literal or unescaped ' in character literal
prog.go:9: missing '
I am not able to understand the exact reason behind this as in for example Python, Perl one can declare a string with both single and double quote.
答案1
得分: 93
在Go语言中,'⌘'
表示一个单个字符(称为Rune),而"⌘"
表示包含字符⌘
的字符串。
这在许多编程语言中都是正确的,其中字符串和字符之间的区别是显著的,比如C++。
在Go博客关于字符串的"Code points, characters, and runes"部分中可以了解更多信息。
英文:
In Go, '⌘'
represents a single character (called a Rune), whereas "⌘"
represents a string containing the character ⌘
.
This is true in many programming languages where the difference between strings and characters is notable, such as C++.
Check out the "Code points, characters, and runes" section in the Go Blog on Strings
答案2
得分: 4
另一种选择,如果你想要嵌入双引号:
package main
func main() {
s := `west "north" east`
println(s)
}
https://golang.org/ref/spec#raw_string_lit
英文:
Another option, if you are wanting to embed double quotes:
package main
func main() {
s := `west "north" east`
println(s)
}
答案3
得分: 1
Go是一种静态类型的语言。同时,Go不是一种脚本语言。尽管我们看到Go的运行方式类似于脚本语言,但它实际上是编译我们编写的源代码,然后执行主函数。因此,我们应该将Go视为C、Java、C++,其中单引号'
用于声明字符(rune, char
),而不是像Python或JavaScript这样的脚本语言。
我认为由于Go是一种新语言,而当前的趋势是脚本语言,所以产生了这种混淆。
英文:
Go is a statically typed language. Also Go is not a scripting language. Though we see Go is running like a scripting language, it is compiling the source we write and then execute the main function. So, we should treat Go as C, Java, C++ where single quote '
is used to declare characters (rune, char
) unlike scripting languages like Python or JavaScript.
I think as this is a new language, and current trend is lying with scripting languages, this confusion has been occurred.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论