Looping thorugh the Alphabet in GoLang

In a recent Go programming task I needed to loop through the letters from a to z. I also needed the capital letter from A to Z. For-looping thorugh the letters in Go is luckily a breeze.

The easiest way is just using a Rune. A Rune is an int32 which represent a unicode character. As a rune (the variable r below) is a Unicode character, it allows me to use the ToUpper() from the unicode package to find the Uppercase version of the letter.

Do note that a rune is not a string, and if you need the rune used in string context, then you need to convert it to a string (see stringR variable below).

package main

import (
	"fmt"
	"unicode"
)

func main() {
	//	testString := "dabAcCaCBAcCcaDA"

	for r := 'a'; r < 'z'; r++ {
		R := unicode.ToUpper(r)
		fmt.Printf("%c%c\n", r, R)

		stringR := fmt.Sprintf("%c%c", r, R)
		fmt.Println(stringR)
	}

}

Have a Go on the Go Playground.