Sobes.tech
Intern

What is the string data type in the Go language and how is it used?

sobes.tech AI

Answer from AI

The string data type in Go represents an immutable sequence of bytes. In Go, strings are handled as byte slices but with an additional guarantee of immutability.

Key features:

  • Immutability: Once created, a string cannot be changed. Any operation that appears to modify a string actually creates a new string.
  • UTF-8 encoding: Go uses UTF-8 by default for strings, allowing convenient handling of text in various languages. Individual characters in a string (runes) can occupy different numbers of bytes.
  • Byte sequence: A string is a sequence of bytes. Accessing s[i] returns a byte, not a rune. To work with runes, use []rune(s) or a for range s loop.
  • Length: The built-in function len(s) returns the number of bytes in the string, not the number of characters (runes).
  • Literal syntax: String literals are enclosed in double quotes "..." or backticks for raw strings `...`.

Usage:

// Declaration and initialization
var s1 string = "hello"
s2 := "world"

// Concatenation
s3 := s1 + " " + s2 // Creates a new string

// Byte length
byteLength := len(s3) // Number of bytes

// Iterating over runes
for i, r := range s3 {
	// i - index of the start of the rune in bytes
	// r - rune (type rune, which is an alias for int32)
	//fmt.Printf("Index: %d, Rune: %c, Type: %T\n", i, r, r)
}

// Converting to byte slice
byteSlice := []byte(s3)

// Converting to rune slice
runeSlice := []rune(s3) // Useful for working with individual characters

// Accessing byte by index (not rune!)
firstByte := s3[0] // byte 'h'

// String slicing
substring := s3[6:] // Creates a new string "world"

// Comparing strings
if s1 == "hello" {
	// Content comparison
}