Question
I want to generate a random string of a fixed length in Go using only alphabetic characters (A-Z and a-z), with no digits or symbols. What is the simplest and fastest way to do this?
Short Answer
By the end of this page, you will understand how to generate random strings in Go, how to limit the characters to uppercase and lowercase letters only, and when to choose a simple approach versus a more secure one.
Concept
Random string generation in Go usually means:
- choosing a set of allowed characters
- picking characters from that set at random
- repeating until the string reaches the required length
For this question, the allowed character set is only letters:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
The core idea is that a random string is built one character at a time. For each position in the string, your program randomly selects one character from the allowed alphabet.
This matters in real programming because random strings are often used for:
- temporary identifiers
- invite codes
- test data
- filenames
- mock tokens
In Go, there are two common ways to generate random values:
math/randfor general-purpose pseudo-random valuescrypto/randfor security-sensitive randomness
If you only want a simple random-looking string for testing or non-sensitive use, math/rand is often enough. If the string is used for passwords, reset tokens, API secrets, or anything security-related, use crypto/rand instead.
A fixed-length random string is not about generating one random word. It is about repeatedly sampling from a known alphabet until you have enough characters.
Mental Model
Imagine you have a bag containing 52 tiles:
- 26 lowercase letters
- 26 uppercase letters
To build a random string of length 8:
- reach into the bag
- pick one tile
- write it down
- put the tile back
- repeat 8 times
That is exactly what the code does. The string length tells you how many picks to make, and the alphabet string is the bag of available characters.
Syntax and Examples
Basic approach with math/rand
package main
import (
"fmt"
"math/rand"
"time"
)
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
func randomString(n int) string {
rand.Seed(time.Now().UnixNano())
b := make([]byte, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
func main() {
fmt.Println(randomString(10))
}
How it works
lettersstores all allowed characters.make([]byte, n)creates space forncharacters.rand.Intn(len(letters))picks a random index.- Each byte in
bis filled with one random letter. string(b)converts the byte slice into a Go string.
Step by Step Execution
Consider this function:
const letters = "abcXYZ"
func randomString(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
If we call:
rand.Seed(1)
fmt.Println(randomString(4))
Here is the step-by-step idea:
-
letterscontains 6 possible characters:abcXYZ
-
make([]byte, 4)creates a byte slice with space for 4 characters.
Real World Use Cases
Random fixed-length letter strings are useful in many situations:
- Test data generation
- Create fake usernames like
AbCdEf.
- Create fake usernames like
- Temporary file labels
- Generate readable suffixes for filenames.
- Invite or referral codes
- If security is not critical, a short random letter code may be enough.
- Mock API responses
- Simulate IDs or labels in development.
- Games and simulations
- Generate random names, room codes, or labels.
If the string protects access to something important, do not use math/rand. Use crypto/rand instead.
Real Codebase Usage
In real projects, developers usually wrap this logic in a small helper function so it can be reused across the codebase.
Common patterns include:
Validation
Check that the requested length is valid.
func randomString(n int) string {
if n <= 0 {
return ""
}
b := make([]byte, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
Early return
Guard clauses keep the function simple.
if n <= 0 {
return ""
}
Reusable alphabet configuration
Developers often make the allowed characters configurable.
func randomFromCharset(n int, charset string) string {
n <= || (charset) == {
}
b := ([], n)
i := b {
b[i] = charset[rand.Intn((charset))]
}
(b)
}
Common Mistakes
1. Seeding every time the function is called
This is a very common beginner mistake.
Problematic code
func randomString(n int) string {
rand.Seed(time.Now().UnixNano())
b := make([]byte, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
Why it is a problem
- It repeats work unnecessarily.
- Calls made very close together can behave poorly.
- Seeding should usually happen once.
Better
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println(randomString(8))
}
2. Using math/rand for secrets
Broken choice
// Not suitable for password reset tokens
code := randomString(32)
Why it is a problem
is predictable compared with cryptographic randomness.
Comparisons
| Approach | Best for | Fast | Secure | Notes |
|---|---|---|---|---|
math/rand + letters string | Simple random strings, tests, demos | Yes | No | Easiest option |
crypto/rand + letters string | Tokens, passwords, sensitive values | No | Yes | Slower but secure |
| Random bytes encoded as hex/base64 | Binary-safe IDs | Yes/Medium | Can be | Usually includes digits or symbols |
math/rand vs crypto/rand
| Feature |
|---|
Cheat Sheet
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
Simple function
func randomString(n int) string {
if n <= 0 {
return ""
}
b := make([]byte, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
Seed once
rand.Seed(time.Now().UnixNano())
Secure version
- Use
crypto/rand - Return
(string, error) - Use it for tokens, secrets, and passwords
Rules to remember
- Use a fixed alphabet when you want only certain characters.
- Use
math/randfor non-sensitive randomness. - Use
crypto/randfor security-sensitive randomness.
FAQ
How do I generate a random string with letters only in Go?
Create a string containing all allowed letters, then repeatedly pick random indexes from it and build a result string.
Is math/rand good enough for random strings in Go?
Yes for testing, demos, and non-sensitive values. No for passwords, tokens, or anything security-related.
How do I include both uppercase and lowercase letters?
Use an alphabet like:
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
Why should I seed math/rand only once?
Seeding initializes the pseudo-random generator. Doing it once is cleaner and avoids unnecessary repeated setup.
Should I use bytes or runes for this?
Use bytes if your alphabet is only ASCII letters. Use runes if you need Unicode characters.
What happens if the requested length is 0?
A good helper function should return an empty string.
How can I make the function reusable for other character sets?
Pass the character set as a parameter, such as randomFromCharset(n, charset).
Mini Project
Description
Build a small Go utility that generates random invitation codes made of uppercase and lowercase letters only. This demonstrates how to define an allowed character set, pick random characters, validate input, and reuse the logic in a practical program.
Goal
Create a Go program that generates one or more fixed-length random letter-only codes from the command line.
Requirements
- Create a function that generates a random string of a given length using only
A-Zanda-z. - Return an empty string if the requested length is 0 or negative.
- Seed the random generator once before generating codes.
- Print at least three random codes of the same length.
- Keep the implementation limited to non-secure randomness using
math/rand.
Keep learning
Related questions
Check if a Value Exists in a Slice in Go
Learn how to check whether a value exists in a slice in Go, and why Go has no Python-style `in` operator for arrays or slices.
Concatenating Slices in Go with append
Learn how to concatenate two slices in Go using append and the ... operator, with examples, pitfalls, and practical usage.
Convert String to Integer in Go: Idiomatic Parsing with strconv.Atoi
Learn the idiomatic way to convert a string to an int in Go using strconv.Atoi, with examples, errors, and common mistakes.