How to Convert a String to Uppercase or Lowercase in Go

Use the `strings` package functions `ToUpper` and `ToLower` to convert strings, as Go does not have built-in methods on the `string` type itself.

Use the strings package functions ToUpper and ToLower to convert strings, as Go does not have built-in methods on the string type itself. These functions handle Unicode characters correctly, unlike simple byte manipulation which would fail on non-ASCII characters.

Here is a practical example showing how to use both functions:

package main

import (
	"fmt"
	"strings"
)

func main() {
	input := "Hello, World! 你好"

	// Convert to uppercase
	upper := strings.ToUpper(input)
	fmt.Println(upper) // Output: HELLO, WORLD! 你好

	// Convert to lowercase
	lower := strings.ToLower(input)
	fmt.Println(lower) // Output: hello, world! 你好
}

If you need to change only the first letter of a string (title case), use strings.Title or strings.ToTitle, though Title is deprecated in newer Go versions in favor of ToTitle for better Unicode support. Note that ToTitle converts the first character of each word to title case, not just the first letter of the sentence.

package main

import (
	"fmt"
	"strings"
)

func main() {
	input := "go programming"
	
	// Convert first letter of each word to title case
	titled := strings.ToTitle(input)
	fmt.Println(titled) // Output: Go Programming
}

Remember that these functions return a new string and do not modify the original, since Go strings are immutable. If you are working with large strings in a performance-critical loop, consider reusing a strings.Builder to avoid excessive allocations, though for most standard use cases, the direct function calls are sufficiently efficient.

Avoid manual byte iteration for case conversion unless you are certain the input is strictly ASCII, as this will produce incorrect results for characters outside the 0-127 range. The strings package handles the complexity of Unicode case folding internally, ensuring consistent behavior across different languages and character sets.