"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Tips for converting numbers into letters in Go language

Tips for converting numbers into letters in Go language

Posted on 2025-04-13
Browse:511

How to Convert Numbers to Letters in Go?

Alphabetic Representation of Numbers in Go

Converting a number to a letter in Golang can be achieved in several ways.

Number -> rune

Simply add the number to the constant 'A' - 1 to obtain the corresponding rune:

func toChar(i int) rune {
    return rune('A' - 1   i)
}

Number -> String

If a string is desired, the following function can be used:

func toCharStr(i int) string {
    return string('A' - 1   i)
}

Number -> String (Cached)

To optimize multiple conversions, the corresponding strings can be stored in an array and the array index used to retrieve the string:

var arr = [...]string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
    "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}

func toCharStrArr(i int) string {
    return arr[i-1]
}

Number -> String (Slicing String Constant)

An efficient solution involves slicing a string constant:

const abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

func toCharStrConst(i int) string {
    return abc[i-1 : i]
}

These solutions provide convenient ways to convert numbers to their corresponding alphabetic representations in Go.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3