string 无法在 golang 中用单引号分配字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34691045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:30:05  来源:igfitidea点击:

Cannot assign string with single quote in golang

stringgo

提问by shivams

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.

我正在学习 go,在玩字符串时,我注意到如果字符串是单引号,那么 golang 会给我一个错误,但双引号工作正常。

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.

我无法理解这背后的确切原因,例如在 Python 中,Perl 可以声明一个带有单引号和双引号的字符串。

回答by ti7

In Go, '?'represents a single character (called a Rune), whereas "?"represents a string containing the character ?.

在 Go 中,'?'表示单个字符(称为 Rune),而"?"表示包含字符 的字符串?

This is true in many programming languages where the difference between strings and characters is notable, such as C++.

在字符串和字符之间的区别很明显的许多编程语言中都是如此,例如 C++。

Check out the "Code points, characters, and runes" section in the Go Blog on Strings

查看Go 字符串博客中的“代码点、字符和符文”部分

回答by Jawadh Salih Rifath

Go is a statically typed language. Also GOis not a scripting language. Though we see GOis running like a scripting language, it is compiling the source we write and then execute the main function. So, we should treat GOas C, JAVA, C++where single quote ''is used to declare characters (rune, char) unlike scripting languages like Python or JavaScript.

Go 是一种静态类型语言。另外GO是不是一种脚本语言。虽然我们看到GO它像脚本语言一样运行,但它正在编译我们编写的源代码,然后执行 main 函数。因此,与 Python 或 JavaScript 等脚本语言不同,我们应该将其GO视为使用C, JAVA, C++单引号''来声明字符 ( rune, char) 的地方。

I think as this is a new language, and current trend is lying with scripting languages, this confusion has been occurred.

我认为由于这是一种新语言,而当前的趋势是脚本语言,因此出现了这种混乱。