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

标签 string go

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

func main() {
    var a string
    a = 'hello' //will give error
    a = "hello" //will not give error
}

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

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 可以用单引号和双引号声明一个字符串。

最佳答案

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

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

查看 Go Blog on Strings 中的“代码点、字符和 rune ”部分

关于string - 无法在golang中用单引号分配字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34691045/

相关文章:

websocket - 将 go websocket 库更新到最新版本

javascript - 将字符串拆分为行和句子,但忽略缩写

c++ - 从字符串中删除空格 - 带指针的就地 C 样式

c++ - C++ 中 + 的运算符重载

Go编译器技巧

postgresql - Postgresql 的 Golang 过程语言

go - 使用go从ftp服务器解压部分gz文件

java - 将扫描仪输入永久存储到字符串中

python - 在 python 中识别字符串中的子字符串的最有效方法?

unit-testing - 安装go with homebrew,找不到$GOROOT导致包失败