In the earlier tutorials, we have seen how to define variables and how to define constants in Google Go. This tutorial explains how we can use strings in Google Go programming.
Strings
The predeclared string type is string. Unlike C/C++ programming, Strings are length-delimited not NUL-terminated. Strings behave like arrays of bytes but are immutable: once created, it is impossible to change the contents of a string. In C++ terms, Go strings are a bit like const strings, while pointers to strings are analogous to const string references. Once you’ve built a string value, you can’t change it, although of course you can change a string variable simply by reassigning it.
This snippet from strings.go is legal code:
s := "hello"
if s[1] != 'e' { os.Exit(1) }
s = "good bye"
var p *string = &s
*p = "ciao"
However the following statements are illegal because they would modify a string value:
s[0] = 'x' (*p)[1] = 'y'
The elements of strings have type byte and may be accessed using the usual indexing operations. It is illegal to take the address of such an element; if s[i] is theith byte of a string, &s[i] is invalid.
String literals
A string literal represents a string constant obtained from concatenating a sequence of characters. There are two forms: raw string literals and interpreted string literals.
Raw string literals are character sequences between back quotes ` `. Within the quotes, any character is legal except back quote. When using back quotes, backslashes have no special meaning and the string may span multiple lines.
Interpreted string literals are character sequences between double quotes ” “. The text between the quotes, which may not span multiple lines, forms the value of the literal, with backslash escapes interpreted as they are in character literals.
Below are some examples of both types of string literals. Google Go also supports Unicode strings.
`abc` // same as "abc" `\n \n` // same as "\\n\n\\n" "\n" "" "Hello, world!\n" "日本語" // UTF-8 input text `日本語` // UTF-8 input text as a raw literal
Strings can be concatenated using the ‘+’ operator. The length of string s can be discovered using the built-in function len(). The length is a compile-time constant if s is a string literal.
var string1 = "Hello World " var string2 = "This is Google Go" string3 := string1 + string2 //string3 = "Hello World This is Google Go" len_string3 := len(string3) //len_string3 = 29
Google Go provides a “strings” package that consists of several functions to manipulate strings. You can find more information at http://golang.org/pkg/strings/.
Related Posts:
Tags: google go

