← 中文资源

简体中文版本

用 sync.OnceValue 惰性编译正则

借助 sync.OnceValue 把正则编译推迟到首次校验时执行,多 goroutine 并发安全复用同一个已编译匹配器,免去手写锁。

阅读英文原文

实现说明

活动部件是函数 isValidInvoice、main。 for i, code := range candidates 承担全部的逐项处理。goroutine 把工作从当前执行流上接走。清理逻辑用 defer 挂载,函数的任何退出路径都会执行。

使用要点

  • 没有安装步骤:用到的 API 全部随平台提供。
  • 每一步打印都带着自己的标签:compiling invoice regex once。
  • main 按顺序串起 isValidInvoice;运行文件就会把这个流程跑一遍。

常见问题

运行「用 sync.OnceValue 惰性编译正则」会打印什么?

运行文件本身,compiling invoice regex once 这些前缀各对应一段演示逻辑。

签名一览:func isValidInvoice(code string) bool

核心语句

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)
}

代码示例

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])
	}
}