https://github.com/szmcdull/go-weakref
https://github.com/szmcdull/go-weakref
go golang weakref
Last synced: 4 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/szmcdull/go-weakref
- Owner: szmcdull
- Created: 2022-09-09T12:46:12.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2023-09-08T14:03:04.000Z (over 2 years ago)
- Last Synced: 2024-06-20T09:18:59.794Z (almost 2 years ago)
- Topics: go, golang, weakref
- Language: Go
- Homepage:
- Size: 16.6 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# go-weakref
A generic weak reference in Go. Inspired by https://github.com/ivanrad/go-weakref
It is (naively) tested against race conditions.
# Usage
```go
package main
import (
"errors"
"fmt"
"runtime"
"time"
"github.com/szmcdull/go-weakref"
)
func main() {
v := 123
wr := weakref.NewWeakRef(&v)
fmt.Println(weakref.IsAlive(wr)) // true
fmt.Println(*weakref.Get(wr)) // 123
runtime.KeepAlive(v)
runtime.GC()
time.Sleep(time.Millisecond)
runtime.GC()
time.Sleep(time.Millisecond)
fmt.Println(weakref.IsAlive(wr)) // false
err := errors.New(`456`)
wi := weakref.NewWeakInterface(err)
fmt.Println(weakref.GetInterface(wi).Error()) // 456
runtime.KeepAlive(err)
//weakref.NewWeakRef(errors.New(`123`)) // compiler error: NewWeakRef expects a pointer argument
//weakref.NewWeakInterface(123) // panic, 123 is not a interface
//weakref.NewWeakInterface(any(123)) // panic, 123 is a non-pointer interface
}
```