options

package
v1.13.14-0.3.0.release Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2025 License: GPL-3.0 Imports: 0 Imported by: 0

Documentation

Overview

Package options provides a generic mechanism for defining configuration of arbitrary types.

Example
package main

import (
	"fmt"

	"github.com/ava-labs/libevm/libevm/options"
)

// config is an arbitrary type to be configured with [options.Option] values.
// Although it can be exported, there is typically no need.
type config struct {
	num  int
	flag bool
}

// An Option configures an arbitrary type. Using a type alias (=) instead of a
// completely new type is recommended as it maintains compatibility with helpers
// such as [options.Func].
type Option = options.Option[config]

func WithNum(n int) Option {
	return options.Func[config](func(c *config) {
		c.num = n
	})
}

func WithFlag(b bool) Option {
	return options.Func[config](func(c *config) {
		c.flag = b
	})
}

func main() {
	num42 := WithNum(42)
	flagOn := WithFlag(true)

	// Some IDEs and linters might complain about the redundant type parameter
	// as it can be inferred, but it makes for more readable code.
	fromZero := options.As[config](num42, flagOn)
	fmt.Printf("From zero value: %T(%+[1]v)\n", fromZero)

	fromDefault := options.ApplyTo(&config{
		num: 100,
	}, flagOn)
	fmt.Printf("Applied to default value: %T(%+[1]v)\n", fromDefault)

}
Output:

From zero value: *options_test.config(&{num:42 flag:true})
Applied to default value: *options_test.config(&{num:100 flag:true})

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplyTo

func ApplyTo[T any](t *T, opts ...Option[T]) *T

ApplyTo applies Options to the T and returns it for convenience.

func As

func As[T any](opts ...Option[T]) *T

As applies Options to a zero-value T, which it then returns.

Types

type Func

type Func[T any] func(*T)

A Func converts a function into an Option, using itself as the Configure method.

func (Func[T]) Configure

func (f Func[T]) Configure(t *T)

Configure implements the Option interface.

type Option

type Option[T any] interface {
	Configure(*T)
}

An Option configures values of arbitrary type.

Jump to

Keyboard shortcuts

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