Compile Regex Once With sync.OnceValue
Defer compiling a regexp until first validation with sync.OnceValue, so concurrent goroutines share one compiled matcher without manual locks.
Code
package main
import (
"fmt"
"regexp"
"sync"
)
var invoiceCodePattern = sync.OnceValue(func() *regexp.Regexp {
fmt.Println("compiling invoice regex once")
return regexp.MustCompile(`^INV-[0-9]{4}-[A-Z]{2}$`)
})
func isValidInvoice(code string) bool {
return invoiceCodePattern().MatchString(code)
}
func main() {
candidates := []string{"INV-2026-EU", "bad-code", "INV-1042-US", "INV-99-JP"}
results := make([]bool, len(candidates))
var wg sync.WaitGroup
for i, code := range candidates {
wg.Add(1)
go func(idx int, value string) {
defer wg.Done()
results[idx] = isValidInvoice(value)
}(i, code)
}
wg.Wait()
for i, code := range candidates {
fmt.Printf("%-12s valid=%t\n", code, results[i])
}
}Runtime walkthrough — Compile Regex Once With sync.OnceValue
Dynamic state transitions occur strictly insides isValidInvoice and main.
for i, code := range candidates handles sequential element processing cleanly inside this block. A goroutine takes the work off the current one. Cleanup is attached with defer, so it runs on every exit path of the function.
Points of care
- Installation step skipped: native platform libraries include all referenced calls.
Applying it
The entry-point signature is func isValidInvoice(code string) bool
Runtime logs descriptive prefixes — compiling invoice regex once — when the file runs.
main sequences isValidInvoice; executing the file runs that flow once.
Statements that matter
var invoiceCodePattern = sync.OnceValue(func() *regexp.Regexp {
fmt.Println("compiling invoice regex once")
return regexp.MustCompile(`^INV-[0-9]{4}-[A-Z]{2}$`)
})
func isValidInvoice(code string) bool {
return invoiceCodePattern().MatchString(code)
}
for i, code := range candidates {
wg.Add(1)
go func(idx int, value string) {
defer wg.Done()
results[idx] = isValidInvoice(value)
}(i, code)
}
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.
FAQ
- What does Compile Regex Once With sync.OnceValue print when run?
- Execute the whole file; each printed line is prefixed with a label like `compiling invoice regex once`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.