weak

package
v0.0.0-...-b05aa3b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 3, 2019 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package weak implement weak reference

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Wrap

func Wrap(x interface{}) (Strong, Weak)

Wrap object x into strong/weak references pair. Wrap(nil) will panic.

Types

type Pool

type Pool struct {
	sync.Mutex

	New func(name string) interface{}
	// contains filtered or unexported fields
}

Pool is a object pool which share object by name

func (*Pool) Get

func (p *Pool) Get(name string) (ref Strong)

type Strong

type Strong interface {
	// Get the referenced data. it's always not nil, because Wrap(nil) is not allowed
	Get() interface{}
	// Get the corresponding weak reference
	Weak() Weak
}

Strong reference

type Weak

type Weak interface {
	// Get the referenced data, this function will return nil when all strong references are finalized.
	Get() interface{}
	// Get a strong reference
	Strong() (Strong, bool)
}

Weak reference

Example
s, w := Wrap(new(int)) // wrap data into strong reference
_ = s.Weak()           // get the weak reference from the strong one
_ = s.Get().(*int)     // get the referenced data from the strong reference
s = nil                // release the strong reference

// a weak reference can be promoted to a strong one
if s1, ok := w.Strong(); ok {
	fmt.Println("promoted:", s1.Get())
}
// the weak reference may be released at anytime after all the strong references finalized.
if x, ok := w.Get().(*int); ok {
	fmt.Println("*x=", *x)
}
Output:

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL