Reputation: 2717
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.
Upvotes: 57
Views: 37842
Reputation: 18792
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++ 1.
Check out the "Code points, characters, and runes" section in the Go Blog on Strings
1 Note that strings in Go are not null terminated \0
and instead represented by a pointer to their start and an integer length.
Upvotes: 96
Reputation: 460
Double, Single and Back quotes
Double and back quotes can be used to define a string.
Single quotes will not allow to put more than one characters. If a string with escape characters is formatted in double quotes, escape characters can be interpreted. If a string with escape characters is formatted in back quotes, escape characters are ignored.
Single quotes A character is formatted in single quotes can either be a byte or a rune. If we don’t declare the type, the default type will be rune.
Upvotes: 0
Reputation: 150
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.
Upvotes: 1
Reputation: 1
Another option, if you are wanting to embed double quotes:
package main
func main() {
s := `west "north" east`
println(s)
}
https://golang.org/ref/spec#raw_string_lit
Upvotes: 4