Sobes.tech
Junior

How can you work with strings in Go?

sobes.tech AI

Answer from AI

Strings in Go are immutable sequences of bytes. They can represent both UTF-8 text and arbitrary binary data.

Main ways to work with them:

  • Declaration and initialization:

    var s1 string           // Empty string
    s2 := "hello"          // Initialized with a string literal
    s3 := `multiline
    string`                 // Raw string literal
    
  • String length:

    len(s2) // Length in bytes. For "hello" it will be 5.
    
  • Access to bytes:

    b := s2[0] // Get byte at index. Returns 'h' (in UTF-8).
    

    Direct access to bytes does not guarantee getting a UTF-8 character.

  • Access to runes (UTF-8 characters): Strings can be iterated over runes:

    for index, runeValue := range s2 {
        fmt.Printf("Index: %d, Rune: %c\n", index, runeValue)
    }
    

    Length in runes:

    utf8.RuneCountInString(s2) // Length in runes. For "hello" it will be 5.
    
  • String concatenation:

    str1 := "hello"
    str2 := " world"
    result := str1 + str2 // Concatenation with + operator
    

    For efficient concatenation of many strings, use strings.Builder.

    var sb strings.Builder
    sb.WriteString("hello")
    sb.WriteString(" ")
    sb.WriteString("world")
    result := sb.String() // Get the resulting string
    
  • Conversion between strings and byte/rune slices:

    byteslice := []byte(s2)   // String to byte slice
    rs := []rune(s2)          // String to rune slice
    
    backToString := string(byteslice) // Byte slice to string
    backToString = string(rs)         // Rune slice to string
    
  • strings package: Provides many useful functions:

    • Contains, HasPrefix, HasSuffix
    • Index, LastIndex
    • Replace, ToUpper, ToLower, Trim, TrimSpace
    • Split, Join
  • strconv package: For converting strings to other data types (numbers, booleans) and vice versa.

    i, err := strconv.Atoi("123") // String to int
    s := strconv.Itoa(456)        // Int to string
    
  • Immutability: Any operations that seem to modify a string (like concatenation) actually create a new string. This is important to consider for performance when making frequent modifications. In such cases, it's better to use []byte or strings.Builder.