simple

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: May 29, 2023 License: MIT Imports: 5 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache[K comparable, V any] struct {
	// contains filtered or unexported fields
}

Cache is a simple cache has no clear priority for evict cache.

func NewCache

func NewCache[K comparable, V any]() *Cache[K, V]

NewCache creates a new non-thread safe cache.

Example
package main

import (
	"fmt"

	"github.com/alidevhere/go-generics-cache/policy/simple"
)

func main() {
	c := simple.NewCache[string, int]()
	c.Set("a", 1)
	c.Set("b", 2)
	av, aok := c.Get("a")
	bv, bok := c.Get("b")
	cv, cok := c.Get("c")
	fmt.Println(av, aok)
	fmt.Println(bv, bok)
	fmt.Println(cv, cok)
	c.Delete("a")
	_, aok2 := c.Get("a")
	if !aok2 {
		fmt.Println("key 'a' has been deleted")
	}
	// update
	c.Set("b", 3)
	newbv, _ := c.Get("b")
	fmt.Println(newbv)
}
Output:

1 true
2 true
0 false
key 'a' has been deleted
3

func (*Cache[K, V]) Delete

func (c *Cache[K, V]) Delete(key K)

Delete deletes the item with provided key from the cache.

func (*Cache[K, V]) Get

func (c *Cache[K, V]) Get(k K) (val V, ok bool)

Get gets an item from the cache. Returns the item or zero value, and a bool indicating whether the key was found.

func (*Cache[K, _]) Keys

func (c *Cache[K, _]) Keys() []K

Keys returns cache keys. the order is sorted by created.

Example
package main

import (
	"fmt"

	"github.com/alidevhere/go-generics-cache/policy/simple"
)

func main() {
	c := simple.NewCache[string, int]()
	c.Set("foo", 1)
	c.Set("bar", 2)
	c.Set("baz", 3)
	keys := c.Keys()
	for _, key := range keys {
		fmt.Println(key)
	}
}
Output:

foo
bar
baz

func (*Cache[K, V]) Load

func (c *Cache[K, V]) Load(filePath string) error

Loads cache state from file using gob decoder

func (*Cache[K, V]) Save

func (c *Cache[K, V]) Save(filePath string) error

Saves cache state to file using gob encoder

func (*Cache[K, V]) Set

func (c *Cache[K, V]) Set(k K, v V)

Set sets any item to the cache. replacing any existing item. The default item never expires.

Jump to

Keyboard shortcuts

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