Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
name: Go
on: [push]
on:
push:
branches: [main]
pull_request:
jobs:
test:
strategy:
matrix:
go-version:
- '1.24'
- '1.25'
- '1.26'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# weakmap

[![Go Reference](https://pkg.go.dev/badge/github.com/acycl/weakmap.svg)](https://pkg.go.dev/github.com/acycl/weakmap)

A generic cache map implementation with [weak
pointers](https://pkg.go.dev/weak#Pointer) as described [on the Go
blog](https://go.dev/blog/cleanups-and-weak#weak-pointers).
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
module github.com/acycl/weakmap

go 1.24.0
go 1.25.0

require golang.org/x/sync v0.19.0
12 changes: 11 additions & 1 deletion weakmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,22 @@ import (
"weak"
)

// Map is a concurrent cache that stores values as weak pointers. Values are
// created on demand via the New function and automatically removed from the
// cache when they are no longer referenced elsewhere and garbage collected.
//
// A Map must not be copied after first use.
type Map[K comparable, V any] struct {
// New creates a value for the given key. It is called when Load is invoked
// for a key that is not in the cache or whose cached value has been
// collected. If New is nil, Load always returns nil.
New func(K) *V
cache sync.Map
}

// Load retrieves a value from the cache.
// Load retrieves a value from the cache, creating it via New if necessary.
// If the cached value has been garbage collected, New is called again to
// create a fresh value. Returns nil if New is nil.
func (m *Map[K, V]) Load(key K) *V {
if m.New == nil {
return nil
Expand Down