agent

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2026 License: Apache-2.0 Imports: 1 Imported by: 0

Documentation

Overview

Package agent provides a goroutine-safe state container inspired by Elixir's Agent. State is owned by a single goroutine; all access is serialized through channel-based message passing.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetWith

func GetWith[S, R any](a *Agent[S], fn func(S) R) R

GetWith applies fn to the agent's state and returns the result. Unlike Get, the return type R may differ from the state type S. This is a package-level function because Go methods cannot introduce additional type parameters.

Example
package main

import (
	"fmt"

	"github.com/mikehelmick/go-functional/agent"
)

func main() {
	a := agent.New(map[string]int{"a": 1, "b": 2, "c": 3})
	defer a.Stop()
	size := agent.GetWith(a, func(m map[string]int) int { return len(m) })
	fmt.Println(size)
}
Output:
3

Types

type Agent

type Agent[S any] struct {
	// contains filtered or unexported fields
}

Agent holds state of type S in a dedicated goroutine. All operations are goroutine-safe and serialized. Methods must not be called after Stop.

func New

func New[S any](initial S) *Agent[S]

New creates and starts an Agent with the given initial state.

func (*Agent[S]) Cast

func (a *Agent[S]) Cast(fn func(S) S)

Cast applies fn to the current state asynchronously. It returns immediately without waiting for the update to complete.

func (*Agent[S]) Get

func (a *Agent[S]) Get() S

Get returns the current state.

Example
package main

import (
	"fmt"

	"github.com/mikehelmick/go-functional/agent"
)

func main() {
	a := agent.New(42)
	defer a.Stop()
	fmt.Println(a.Get())
}
Output:
42

func (*Agent[S]) Stop

func (a *Agent[S]) Stop()

Stop shuts down the agent. It blocks until the loop goroutine exits. Calling Stop more than once is safe; subsequent calls are no-ops.

func (*Agent[S]) Update

func (a *Agent[S]) Update(fn func(S) S)

Update applies fn to the current state, stores the result, and blocks until the update is complete.

Example
package main

import (
	"fmt"

	"github.com/mikehelmick/go-functional/agent"
)

func main() {
	a := agent.New(0)
	defer a.Stop()
	a.Update(func(s int) int { return s + 10 })
	fmt.Println(a.Get())
}
Output:
10

Jump to

Keyboard shortcuts

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