English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang Basic Tutorial

Golang Control Statements

Golang Function & Method

Golang Struct

Golang Slice & Array

Golang String (String)

Golang Pointer

Golang Interface

Golang Concurrency

Golang Exception (Error)

Golang Other Miscellaneous

Go Language String (String)

in Go language, strings are different from other languages, such as Java, c++、Python, etc. It is a variable-width character sequence, where each character is represented by UTF-8encoding, one or more bytes represent. Or in other words, a string is an immutable chain of arbitrary bytes (including bytes with a value of zero), or a string is a read-only byte slice, the bytes of the string can be used with UTF-8encoding to represent Unicode text.

Due to the adoption of UTF-8Encoding, Golang strings can contain text, text is a mixture of any language in the world without causing page chaos and restrictions. Usually, strings are usedDouble quotes””Quoted, as shown in the following examples:

//How to create a string
package main 
  
import "fmt"
  
func main() { 
  
//Create and initialize
//Variable with a string
//Use shorthand declaration
    My_value_1 := "Welcome to oldtoolbag.com"
  
    //Using the var keyword
    var My_value_2 string 
    My_value_2 = "w3codebox"
  
    //Display the string 
    fmt.Println("String 1: ", My_value_1) 
    fmt.Println("String 2: ", My_value_2) 
}

Output:

String 1: Welcome to oldtoolbag.com
String 2:  w3codebox

Note:A string can be empty, but cannot be nil.

String literals

In Go language, string literals are created in two different ways:

  • Using double quotes (""):Here, string literals are created using double quotes (""). This type of string supports escape characters, as shown in the table below, but does not span multiple lines. This type of string literal is widely used in Golang programs.

    Escape characterDescription
    \\\Backslash (\)
    \000given3with8Unicode character with a bit octal code point
    \'Single quotes ('). They are only allowed in the character literals.
    \"Double quotes (""). They are only allowed in the interpreted string literals.
    \aASCII Bell (BEL)
    \bASCII Backspace (BS)
    \fASCII Form Feed (FF)
    \nASCII Line Feed (LF)
    \rASCII Carriage Return (CR)
    \tASCII Tab (TAB)
    \uhhhhgiven4with16Unicode characters with hexadecimal code points.

    given8with32Unicode characters with hexadecimal code points.
    \vASCII Vertical Tab (VT)
    \xhhgiven2with8Unicode characters with hexadecimal code points.
  • Use backticks (`):Here, the string literal is created using backticks (`), also known asraw literals(Original text). Original text does not support escape characters, can span multiple lines, and can contain any character except backticks. It is usually used to write multiline messages in regular expressions and HTML.

    package main
    import "fmt"
    func main() {
        //Create and initialize
        //Variables with string literals
        //Use double quotes
        My_value_1 := "Welcome to w3codebox"
        //Add an escape character
        My_value_2 := "Welcome!\nw3codebox"
        //Use backticks
        My_value_3 := `Hello!w3codebox`
        //Add an escape character
        //Original text
        My_value_4 := `Hello!\nw3codebox`
        //Display
        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)
    }

    Output:

    String 1: Welcome to w3codebox
    String 2: Welcome!
    w3codebox
    String 3: Hello!w3codebox
    String 4: Hello!\nw3codebox

Key points about strings

  • Strings are immutable:In Go language, once a string is created, it is immutable and the value of the string cannot be changed. In other words, strings are read-only. If you try to change it, the compiler will raise an error.

    //Strings are immutable
    package main 
      
    import "fmt"
      
    func main() { 
      
            //Create and initialize a string
            //Use shorthand declaration
        mystr := "Welcome to w3codebox"
      
        fmt.Println("String:", mystr) 
      
        /* If you try to change the value of a string, the compiler will throw an error, for example, 
         cannot assign to mystr[1] 
           mystr[1]= 'G' 
           fmt.Println("String:", mystr) 
        */
      
    }

    Output:

    String: Welcome to w3codebox
  • How to traverse a string? :You can use the for range loop to traverse a string. This loop can iterate over a string at Unicode code points.

    Syntax:

    for index, chr := range str{
         // statement...
    }

    Here, the index is storing UTF-8The variable for the first byte of the code point encoding, whilechr isA variable to store the characters of the given string, str is the string.

    //Traverse a string
    //Using for range loop
    package main
    import "fmt"
    func main() {
        //A string as the range in a for loop
        for index, s := range "w3codebox" {
            fmt.Printf("%c index value is %d\n", s, index)
        }
    }

    Output:

    The index value is 0
    The index value is 1
    The index value is 2
    The index value is 3
    The index value is 4
  • How to access a single byte of a string?: A string is a byte, so we can access each byte of the given string.

    //Access the bytes of a string
    package main
    import "fmt"
    func main() {
        //Create and initialize a string
        str := "Welcome to w3codebox"
        //Access the bytes of the given string
        for c := 0; c < len(str); c++ {
            fmt.Printf("\nCharacter = %c Byte = %v", str[c], str[c])
        }
    }

    Output:

    Character = W Byte = 87
    Character = e Byte = 101
    Character = l Byte = 108
    Character = c Byte = 99
    Character = o Byte = 111
    Character = m Byte = 109
    Character = e Byte = 101
    Character = Byte = 32
    Character = t Byte = 116
    Character = o Byte = 111
    Character = Byte = 32
    Character = n Byte = 110
    Character = h Byte = 104
    Character = o Byte = 111
    Character = o Byte = 111
    Character = o Byte = 111
  • How to create a string from a slice?:In Go language, it allows you to create a string from a byte slice.

    //Create a string from a slice 
    package main 
      
    import "fmt"
      
    func main() { 
      
        //Create and initialize a byte slice
        myslice1 := []byte{0x47, 0x65, 0x65, 0x6b, 0x73} 
      
        //Create a string from a slice
        mystring1 := string(myslice1) 
      
        //Display the string
        fmt.Println("String 1: ", mystring1) 
      
        //Create and initialize a rune slice 
        myslice2 := []rune{0x0047, 0x0065, 0x0065, 0x006b, 0x0073} 
      
        //Create a string from a slice
        mystring2 := string(myslice2) 
      
        //Display the string
        fmt.Println("String 2: ", mystring2) 
    }

    Output:

    String 1:  Geeks
    String 2:  Geeks
  • How to find the length of a string?:In Golang strings, you can use two functions (one islen(),another isRuneCountInString())to find the length of the string. UTF-8The package provides the RuneCountInString() function, which returns the total number of runes in the string.len()The function returns the number of bytes in the string.

    //Find the length of the string
    package main
    import ("
        "fmt"
        "unicode/utf8"
    )
    func main() {
        //Create and initialize a string
        //Use shorthand declaration
        mystr := "Welcome to w3codebox ??????"
        //Find the length of the string
        //Use the len() function
        length1 := len(mystr)
        //Use the RuneCountInString() function
        length2 := utf8.RuneCountInString(mystr)
        //Display the length of the string
        fmt.Println("string:", mystr)
        fmt.Println("Length 1:", length1)
        fmt.Println("Length 2:", length2)
    }

    Output:

    string: Welcome to w3codebox ??????
    Length 1: 31
    Length 2: 31