In the Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where every character is represented by one or more bytes using UTF-8 Encoding. In other words, strings are the immutable chain of arbitrary bytes(including bytes with zero value) or string is a read-only slice of bytes and the bytes of the strings can be represented in the Unicode text using UTF-8 encoding. Due to UTF-8 encoding Golang string can contain a text which is the mixture of any language present in the world, without any confusion and limitation of the page. Generally, strings are enclosed in double-quotes"", as shown in the below example:
Example:
Go
// Go program to illustrate
// how to create strings
package main
import "fmt"
func main() {
// Creating and initializing a
// variable with a string
// Using shorthand declaration
My_value_1 := "Welcome to GeeksforGeeks"
// Using var keyword
var My_value_2 string
My_value_2 = "GeeksforGeeks"
// Displaying strings
fmt.Println("String 1: ", My_value_1)
fmt.Println("String 2: ", My_value_2)
}
OutputString 1: Welcome to GeeksforGeeks
String 2: GeeksforGeeks
Note: String can be empty, but they are not nil.
String Literals
In Go language, string literals are created in two different ways:
Using double quotes("")
Here, the string literals are created using double-quotes(""). This type of string support escape character as shown in the below table, but does not span multiple lines. This type of string literals is widely used in Golang programs.
Escape character | Description |
---|
\\ | Backslash(\) |
---|
\000 | Unicode character with the given 3-digit 8-bit octal code point |
---|
\' | Single quote ('). It is only allowed inside character literals |
---|
\" | Double quote ("). It is only allowed inside interpreted string literals |
---|
\a | ASCII bell (BEL) |
---|
\b | ASCII backspace (BS) |
---|
\f | ASCII formfeed (FF) |
---|
\n | ASCII linefeed (LF |
---|
\r | ASCII carriage return (CR) |
---|
\t | ASCII tab (TAB) |
---|
\uhhhh | Unicode character with the given 4-digit 16-bit hex code point. |
---|
| Unicode character with the given 8-digit 32-bit hex code point. |
---|
\v | ASCII vertical tab (VT) |
---|
\xhh | Unicode character with the given 2-digit 8-bit hex code point. |
---|
Using backticks(``)
Here, the string literals are created using backticks(``) and also known as raw literals. Raw literals do not support escape characters, can span multiple lines, and may contain any character except backtick. It is, generally, used for writing multiple line message, in the regular expressions, and in HTML.
Example:
Go
// Go program to illustrate string literals
package main
import "fmt"
func main() {
// Creating and initializing a
// variable with a string literal
// Using double-quote
My_value_1 := "Welcome to GeeksforGeeks"
// Adding escape character
My_value_2 := "Welcome!\nGeeksforGeeks"
// Using backticks
My_value_3 := `Hello!GeeksforGeeks`
// Adding escape character
// in raw literals
My_value_4 := `Hello!\nGeeksforGeeks`
// Displaying strings
fmt.Println("String 1: ", My_value_1)
fmt.Println("String 2: ", My_value_2)
fmt.Println("String 3: ", My_value_3)
fmt.Println("String 4: ", My_value_4)
}
OutputString 1: Welcome to GeeksforGeeks
String 2: Welcome!
GeeksforGeeks
String 3: Hello!GeeksforGeeks
String 4: Hello!\nGeeksforGeeks
Important Points About String
Strings are immutable
In Go language, strings are immutable once a string is created the value of the string cannot be changed. Or in other words, strings are read-only. If you try to change, then the compiler will throw an error.
Example:
Go
// Go program to illustrate
// string are immutable
package main
import "fmt"
// Main function
func main() {
// Creating and initializing a string
// using shorthand declaration
mystr := "Welcome to GeeksforGeeks"
fmt.Println("String:", mystr)
/* if you trying to change
the value of the string
then the compiler will
throw an error, i.e,
cannot assign to mystr[1]
mystr[1]= 'G'
fmt.Println("String:", mystr)
*/
}
OutputString: Welcome to GeeksforGeeks
How to iterate over a string?
You can iterate over string using for range loop. This loop can iterate over the Unicode code point for a string.
Syntax:
for index, chr:= range str{
// Statement..
}
Here, the index is the variable which store the first byte of UTF-8 encoded code point and chr store the characters of the given string and str is a string.
Example:
Go
// Go program to illustrate how
// to iterate over the string
// using for range loop
package main
import "fmt"
// Main function
func main() {
// String as a range in the for loop
for index, s := range "GeeksForGeeKs" {
fmt.Printf("The index number of %c is %d\n", s, index)
}
}
Output:
The index number of G is 0
The index number of e is 1
The index number of e is 2
The index number of k is 3
The index number of s is 4
The index number of F is 5
The index number of o is 6
The index number of r is 7
The index number of G is 8
The index number of e is 9
The index number of e is 10
The index number of K is 11
The index number of s is 12
How to access the individual byte of the string?
The string is of a byte so, we can access each byte of the given string.
Example:
Go
// Go program to illustrate how to
// access the bytes of the string
package main
import "fmt"
// Main function
func main() {
// Creating and initializing a string
str := "Welcome to GeeksforGeeks"
// Accessing the bytes of the given string
for c := 0; c < len(str); c++ {
fmt.Printf("\nCharacter = %c Bytes = %x", str[c], str[c])
}
}
// This Code is Contributed By Shivam Tiwari
Output:
Character = W Bytes = 57
Character = e Bytes = 65
Character = l Bytes = 6c
Character = c Bytes = 63
Character = o Bytes = 6f
Character = m Bytes = 6d
Character = e Bytes = 65
Character = Bytes = 20
Character = t Bytes = 74
Character = o Bytes = 6f
Character = Bytes = 20
Character = G Bytes = 47
Character = e Bytes = 65
Character = e Bytes = 65
Character = k Bytes = 6b
Character = s Bytes = 73
Character = f Bytes = 66
Character = o Bytes = 6f
Character = r Bytes = 72
Character = G Bytes = 47
Character = e Bytes = 65
Character = e Bytes = 65
Character = k Bytes = 6b
Character = s Bytes = 73
How to create a string form the slice?
In Go language, you are allowed to create a string from the slice of bytes.
Example:
Go
// Go program to illustrate how to
// create a string from the slice
package main
import "fmt"
// Main function
func main() {
// Creating and initializing a slice of byte
myslice1 := []byte{0x47, 0x65, 0x65, 0x6b, 0x73}
// Creating a string from the slice
mystring1 := string(myslice1)
// Displaying the string
fmt.Println("String 1: ", mystring1)
// Creating and initializing a slice of rune
myslice2 := []rune{0x0047, 0x0065, 0x0065,
0x006b, 0x0073}
// Creating a string from the slice
mystring2 := string(myslice2)
// Displaying the string
fmt.Println("String 2: ", mystring2)
}
Output:
String 1: Geeks
String 2: Geeks
How to find the length of the string?
In Golang string, you can find the length of the string using two functions one is len() and another one is RuneCountInString(). The RuneCountInString() function is provided by UTF-8 package, this function returns the total number of rune presents in the string. And the len() function returns the number of bytes of the string.
Example:
Go
// Go program to illustrate how to
// find the length of the string
package main
import (
"fmt"
"unicode/utf8"
)
// Main function
func main() {
// Creating and initializing a string
// using shorthand declaration
mystr := "Welcome to GeeksforGeeks ??????"
// Finding the length of the string
// Using len() function
length1 := len(mystr)
// Using RuneCountInString() function
length2 := utf8.RuneCountInString(mystr)
// Displaying the length of the string
fmt.Println("string:", mystr)
fmt.Println("Length 1:", length1)
fmt.Println("Length 2:", length2)
}
Output:
string: Welcome to GeeksforGeeks ??????
Length 1: 31
Length 2: 31
Similar Reads
Go Tutorial Go or you say Golang is a procedural and statically typed programming language having the syntax similar to C programming language. It was developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but launched in 2009 as an open-source programming language and mainly used in Google
2 min read
Overview
Go Programming Language (Introduction)Go is a procedural programming language. It was developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but launched in 2009 as an open-source programming language. Programs are assembled by using packages, for efficient management of dependencies. This language also supports env
11 min read
How to Install Go on Windows?Prerequisite: Introduction to Go Programming Language Before, we start with the process of Installing Golang on our System. We must have first-hand knowledge of What the Go Language is and what it actually does? Go is an open-source and statically typed programming language developed in 2007 by Robe
3 min read
How to Install Golang on MacOS?Before, we start with the process of Installing Golang on our System. We must have first-hand knowledge of What the Go Language is and what it actually does? Go is an open-source and statically typed programming language developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but
4 min read
Hello World in GolangHello, World! is the first basic program in any programming language. Letâs write the first program in the Go Language using the following steps:First of all open Go compiler. In Go language, the program is saved with .go extension and it is a UTF-8 text file.Now, first add the package main in your
3 min read
Fundamentals
Identifiers in Go LanguageIn programming languages, identifiers are used for identification purposes. In other words, identifiers are the user-defined names of the program components. In the Go language, an identifier can be a variable name, function name, constant, statement label, package name, or type. Example: package ma
3 min read
Go KeywordsKeywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as an identifier. Doing this will result in a compile-time error. Example: C // Go program to illustrate the // use of key
2 min read
Data Types in GoData types specify the type of data that a valid Go variable can hold. In Go language, the type is divided into four categories which are as follows: Basic type: Numbers, strings, and booleans come under this category.Aggregate type: Array and structs come under this category.Reference type: Pointer
7 min read
Go VariablesA typical program uses various values that may change during its execution. For Example, a program that performs some operations on the values entered by the user. The values entered by one user may differ from those entered by another user. Hence this makes it necessary to use variables as another
9 min read
Constants- Go LanguageAs the name CONSTANTS suggests, it means fixed. In programming languages also it is same i.e., once the value of constant is defined, it cannot be modified further. There can be any basic data type of constants like an integer constant, a floating constant, a character constant, or a string literal.
6 min read
Go OperatorsOperators are the foundation of any programming language. Thus the functionality of the Go language is incomplete without the use of operators. Operators allow us to perform different kinds of operations on operands. In the Go language, operators Can be categorized based on their different functiona
9 min read
Control Statements
Functions & Methods
Functions in Go LanguageIn Go, functions are blocks of code that perform specific tasks, which can be reused throughout the program to save memory, improve readability, and save time. Functions may or may not return a value to the caller.Example:Gopackage main import "fmt" // multiply() multiplies two integers and returns
3 min read
Variadic Functions in GoVariadic functions in Go allow you to pass a variable number of arguments to a function. This feature is useful when you donât know beforehand how many arguments you will pass. A variadic function accepts multiple arguments of the same type and can be called with any number of arguments, including n
3 min read
Anonymous function in Go LanguageAn anonymous function is a function that doesnât have a name. It is useful when you want to create an inline function. In Go, an anonymous function can also form a closure. An anonymous function is also known as a function literal.ExampleGopackage main import "fmt" func main() { // Anonymous functio
2 min read
main and init function in GolangThe Go language reserve two functions for special purpose and the functions are main() and init() function.main() functionIn Go language, the main package is a special package which is used with the programs that are executable and this package contains main() function. The main() function is a spec
2 min read
What is Blank Identifier(underscore) in Golang?_(underscore) in Golang is known as the Blank Identifier. Identifiers are the user-defined name of the program components used for the identification purpose. Golang has a special feature to define and use the unused variable using Blank Identifier. Unused variables are those variables that are defi
3 min read
Defer Keyword in GolangIn Go language, defer statements delay the execution of the function or method or an anonymous method until the nearby functions returns. In other words, defer function or method call arguments evaluate instantly, but they don't execute until the nearby functions returns. You can create a deferred m
3 min read
Methods in GolangGo methods are like functions but with a key difference: they have a receiver argument, which allows access to the receiver's properties. The receiver can be a struct or non-struct type, but both must be in the same package. Methods cannot be created for types defined in other packages, including bu
3 min read
Structure
Arrays
Slices
Slices in GolangSlices in Go are a flexible and efficient way to represent arrays, and they are often used in place of arrays because of their dynamic size and added features. A slice is a reference to a portion of an array. It's a data structure that describes a portion of an array by specifying the starting index
14 min read
Slice Composite Literal in GoThere are two terms i.e. Slice and Composite Literal. Slice is a composite data type similar to an array which is used to hold the elements of the same data type. The main difference between array and slice is that slice can vary in size dynamically but not an array. Composite literals are used to c
3 min read
How to sort a slice of ints in Golang?In Go, slices provide a flexible way to manage sequences of elements. To sort a slice of ints, the sort package offers a few straightforward functions. In this article we will learn How to Sort a Slice of Ints in Golang.ExampleGopackage main import ( "fmt" "sort" ) func main() { intSlice := []int{42
2 min read
How to trim a slice of bytes in Golang?In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you ar
3 min read
How to split a slice of bytes in Golang?In Golang, you can split a slice of bytes into multiple parts using the bytes.Split function. This is useful when dealing with data like encoded strings, file contents, or byte streams that must be divided by a specific delimiter.Examplepackage mainimport ( "bytes" "fmt")func main() { // Initial byt
3 min read
Strings
Strings in GolangIn the Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where every character is represented by one or more bytes using UTF-8 Encoding. In other words, strings are the immutable chain of arbitrary bytes(including bytes
7 min read
How to Trim a String in Golang?In Go, strings are UTF-8 encoded sequences of variable-width characters, unlike some other languages like Java, python and C++. Go provides several functions within the strings package to trim characters from strings.In this article we will learn how to Trim a String in Golang.Examples := "@@Hello,
2 min read
How to Split a String in Golang?In Go language, strings differ from other languages like Java, C++, and Python. A string in Go is a sequence of variable-width characters, with each character represented by one or more bytes using UTF-8 encoding. In Go, you can split a string into a slice using several functions provided in the str
3 min read
Different ways to compare Strings in GolangIn Go, strings are immutable sequences of bytes encoded in UTF-8. You can compare them using comparison operators or the strings.Compare function. In this article,we will learn different ways to compare Strings in Golang.Examplepackage main import ( "fmt" "strings" ) func main() { s1 := "Hello" s2 :
2 min read
Pointers