static

package module
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2026 License: MIT Imports: 2 Imported by: 0

README

static

Static function variables for Go without global var guilt.

Go Reference

Example

package main

import (
	"fmt"

	"codeberg.org/yarmak/static"
)

func counter1() int {
	st := static.State[int]()
	(*st)++
	return (*st)
}

func counter2() int {
	st := static.State[int]()
	(*st)++
	return (*st)
}

func complex(key string) int {
	st := static.State1(func() map[string]int { return make(map[string]int) })
	m := *st
	m[key]++
	return m[key]
}

func multi(a, b, c int) (int, int, int) {
	st := static.State[struct{ a, b, c int }]()
	st.a += a
	st.b += b
	st.c += c
	return st.a, st.b, st.c
}

func main() {
	fmt.Println("counter1:")
	fmt.Println(counter1())
	fmt.Println(counter1())
	fmt.Println(counter1())
	fmt.Println("counter2:")
	fmt.Println(counter2())
	fmt.Println(counter2())
	fmt.Println("complex state:")
	fmt.Println(complex("a"))
	fmt.Println(complex("b"))
	fmt.Println(complex("c"))
	fmt.Println(complex("a"))
	fmt.Println(complex("a"))
	fmt.Println("anon func:")
	f := func() int {
		st := static.State[int]()
		(*st)++
		return (*st)
	}
	fmt.Println(f())
	fmt.Println(f())
	fmt.Println(f())
	fmt.Println("multi:")
	fmt.Println(multi(0, 0, 0))
	fmt.Println(multi(1, 2, 3))
	fmt.Println(multi(10, 10, 10))
}

Output:

counter1:
1
2
3
counter2:
1
2
complex state:
1
1
1
2
3
anon func:
1
2
3
multi:
0 0 0
1 2 3
11 12 13

Documentation

Overview

Package static introduces static variables for functions, encapsulating all the global var guilt within this module.

Methods of this package are safe for concurrent use, but the access to returned pointers may need to be serialized for concurrent use (e.g. by a mutex within that state).

Same type parameter must be used for State calls within one function.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func State

func State[T any]() *T

State is a shorthand for State1(nil)

func State1

func State1[T any](init func() T) (ptr *T)

State1 returns function state pointer initializing new ones with value from init function if it is not nil

Types

This section is empty.

Jump to

Keyboard shortcuts

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