Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot assign string with single quote in golang

Tags:

string

go

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.

like image 621
shivams Avatar asked Jan 09 '16 07:01

shivams


People also ask

How do you handle a single quote in a string?

Use escapeEcmaScript method from Apache Commons Lang package: Escapes any values it finds into their EcmaScript String form. Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.). So a tab becomes the characters '\\' and 't' .

When assigning text to strings you can use single or double quotes?

use double quotes for strings and single quotes for chars. I prefer to use the same quoting across the board and so stick with double quotes for JS.

How do I remove single quotes from a string in Golang?

In your go source files, if you try to use single quotes for a multi-character string literal, you'll get a compiler error similar to illegal rune literal . What you can do instead for removing quotes from the start and end of a string, is use the strings. Trim function to take care of it.


2 Answers

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

like image 155
ti7 Avatar answered Oct 11 '22 14:10

ti7


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

like image 44
Zombo Avatar answered Oct 11 '22 14:10

Zombo