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.

GoForm Validation

Code

snippet
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

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`.