Sobes.tech
Junior — Middle

How is string data processed and managed in Go?

sobes.tech AI

Answer from AI

In the Go language, strings are represented by the string type, which is an immutable sequence of bytes in UTF-8 encoding. Key features and approaches to working with strings:

  • Immutability: strings cannot be changed after creation. To modify, new strings must be created.
  • Working with Unicode: since strings are in UTF-8, the rune type is used for working with characters (runes).
  • Concatenation: strings can be combined using the + operator.
  • Conversion to byte slices or rune slices: for manipulating individual characters or bytes.
  • strings package: contains many functions for searching, replacing, splitting, and other string operations.

Example of string processing in Go:

package main

import (
    "fmt"
    "strings"
)

func main() {
    s := "Привет, мир"
    fmt.Println("String length in bytes:", len(s))

    // Convert to rune slice for counting characters
    runes := []rune(s)
    fmt.Println("Number of characters:", len(runes))

    // Check for substring
    if strings.Contains(s, "мир") {
        fmt.Println("String contains 'мир'")
    }

    // Replace substring
    newStr := strings.ReplaceAll(s, "мир", "Go")
    fmt.Println(newStr)
}