示例的浅拷贝不能隔离结构体中的切片、映射或嵌套指针
原文依据:2 处文档称该模式适用于 pointers、slices、maps,并表示变更不会影响缓存,但示例只执行 copy := *u。这只复制顶层结构体;其中的切片、映射和嵌套指针仍共享底层数据。
调用者修改嵌套可变字段时,仍可能改变缓存中的共享对象,引发数据串扰或并发竞态;这正是该配置声称要避免的问题。
文档把该模式称为缓存可变指针、切片和映射时的必需措施,并声称调用方修改不会影响缓存,但示例中的 `copy := *u` 只是浅拷贝。若 User 含切片、映射或嵌套指针,底层数据仍被共享,并发修改仍可能造成竞态或污染缓存。仅含值字段时该示例可正常隔离。用户可要求作者明确浅拷贝限制、提供深拷贝示例,并对含引用字段的类型运行竞态测试。
## Copy-on-Read / Copy-on-WriteRequired when cached values are mutable (pointers, slices, maps):```gocache := hot.NewHotCache[string, *User](hot.WTinyLFU, 10_000). WithTTL(5 * time.Minute). WithCopyOnRead(func(u *User) *User { copy := *u return © }). WithCopyOnWrite(func(u *User) *User { copy := *u return © }). WithJanitor(). Build()defer cache.StopJanitor()```查看另外 1 个位置
- **CopyOnRead** — clones at retrieval: callers get independent copies, mutations don't affect cache- **CopyOnWrite** — clones at storage: cache holds a snapshot, external mutations to the original don't corrupt cached value- Use both when callers read and write concurrently. Use only one when the mutation direction is known.