dqm83011
2016-01-09 07:48
浏览 504
已采纳

无法在Golang中使用单引号分配字符串

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.

图片转代码服务由CSDN问答提供 功能建议

我正在学习go,在玩字符串时,我发现如果字符串用单引号引起来,那么golang就会给我 错误,但双引号可以正常工作。

  func main(){
 var a string 
a ='hello'//将给出错误
a =“ hello” //将不给出错误
}  
   
 
 

这是我在系统上遇到的错误:

 非法符文文字
    
 
 

当我尝试在操场上做同样的事情时,出现此错误:

  prog.go:9:缺少'\  nprog.go:9:语法错误:意外的名称,应使用分号或换行符,或者} 
prog.go:9:字符串中的换行符
prog.go:9:空字符文字或字符文字中未转义的
prog.go:9  :缺少'
   
 
 

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

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongpaozhi5734 2016-01-09 07:59
    已采纳

    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

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongpu1881 2018-10-31 06:57

    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.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题