Strings
A Go string is a read-only data type that represents a UTF-8 encoded slice of bytes.
As in many other languages, strings in Go are sequences of characters. Strings are immutable. Once a string is created in Go, its value cannot be changed. Attempts at changing it will result in the compiler throwing an error message. This is a key difference between strings in Go and strings in other languages.
String Literals
In Go, a string literal is a sequence of characters enclosed either within double-quotes ""
(also called interpreted literals) or backticks ``
(also called raw string literals).
There are some differences between using interpreted or raw string literals. The most important ones are that interpreted literals support escape characters but do not span multiple lines, while raw string literals do not support escape characters, cannot contain backticks, and can span multiple lines.
Here is an example of how strings are defined and printed in Go using double quotes ""
:
package mainimport "fmt"func main() {string_name := "This is an interpreted literal string" // This defines the string.fmt.Println(string_name) // This prints the string.}
Here is an example of how strings are defined and printed in Go using backticks ``
:
package mainimport "fmt"func main() {string_name := `This is a raw string literal` // This defines the string.fmt.Println(string_name) // This prints the string.}
String Escapes
As mentioned previously, escape characters are only supported in interpreted literals (an interpreted literal is a string that uses double quotes ""
). The following is a list of some useful escape characters supported by Go strings:
Description | Escape Character |
---|---|
Single quote | \' |
Double quote | \" |
Backslash | \\ |
New line | \n |
Horizontal tab | \t |
Vertical tab | \v |
Backspace | \b |
Carriage return | \r |
Go to next page | \f |
Escape characters are useful to avoid ambiguities when the string being created has a character that may be problematic. An example of this would be defining "There is no "I" in TEAM"
as an interpreted string literal. Since the string has double quotes in it, the compiler would throw an error message. This can be avoided by using the double quote escape character \"
. The following shows an example where the compiler would throw an error message due to double quotes being used within an interpreted string literal:
package mainimport "fmt"func main() {string_name := "There is no "I" in TEAM" // This line attempts to define the string, but causes an error.fmt.Println(string_name) // This line would print the string if it had been correctly defined.}
After running this code, the compiler will output a message like this:
# command-line-arguments./main.go:5:32: syntax error: unexpected I at end of statement
This issue is solved by using the double quote escape character \"
like this:
package mainimport "fmt"func main() {string_name := "There is no \"I\" in TEAM" // This defines the string.fmt.Println(string_name) // This prints the string.}
String Functions
The strings
package contains many different string functions used to manipulate strings. The strings
package must be imported before using these functions, as in the example below:
package mainimport ("fmt""strings")func main() {name := "Codecademy"find := "d"fmt.Println(find, "is in", name, "at index", strings.Index(name,find))}
Below is a selection of string functions from the strings
package.
Strings
- Compare()
- Compares two strings in lexicographical order.
- Contains()
- Returns a boolean value indicating whether a given substring is present or not in a given string.
- Count()
- Returns the number of times a substring occurs in a given string.
- Cut()
- Slices a string around a separator.
- CutPrefix()
- Returns a given string with the specified prefix removed and a boolean value confirming if the prefix was present.
- CutSuffix()
- Returns a given string with the specified suffix removed and a boolean value confirming if the suffix was present.
- Fields()
- Splits a string into substrings based on whitespace and returns a slice of the substrings.
- HasPrefix()
- Returns a boolean value indicating whether a given string begins with a given prefix.
- HasSuffix()
- Checks if a given suffix exists on the specified string. Returns true if the string has the given suffix, else it returns false.
- Index()
- Returns the index value of the first occurrence of a substring in the original string.
- Join()
- Returns the concatenated elements of a string slice into a single string.
- LastIndex()
- Returns the index value of the last occurrence of a substring in the original string.
- Map()
- Returns a copy of a provided string with its characters modified according to a given mapping function.
- Replace()
- Replaces occurrences of a specified substring within a given string with another substring.
- ToLower()
- Converts a string to lowercase.
- ToUpper()
- Returns a string in all uppercase.
- Trim()
- Removes leading and trailing characters from a string based on the given input.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.