named.go
named.go - Overview
-
Overview This file defines the
Named
interface and theNamedMap
struct, which are used to manage a collection of factories that implement theNamed
interface. It provides methods to create, retrieve, and manage these named factories, ensuring uniqueness of names. -
Detailed Documentation
Named Interface
-
Purpose: Interface implemented by all types of factories that have a name.
type Named interface {
Name() Name
}- Name(): Returns the
Name
of the factory. Return type isName
.
- Name(): Returns the
NamedMap Struct
-
Purpose: Holds a map of factories, where each factory is associated with a
Name
. Also maintains the order in which factories were added.type NamedMap[T Named] struct {
factories map[Name]T
factoriesInOrder []T
}- factories: A map of
Name
toT
(where T implementsNamed
). - factoriesInOrder: A slice of
T
maintaining the insertion order.
- factories: A map of
NewNamedMap Function
-
Purpose: Creates a new
NamedMap
from a list of factories. Returns an error if any of the factories have duplicate names.func NewNamedMap[T Named](factories ...T) (NamedMap[T], error) {
- Parameters:
factories
-...T
: A variadic parameter representing a slice of factories that implement theNamed
interface.
- Returns:
NamedMap[T]
: The newNamedMap
instance.error
: An error if duplicate factory names are found; otherwise,nil
.
- Parameters:
MustNewNamedMap Function
-
Purpose: Creates a new
NamedMap
from a list of factories. Panics if the factories have duplicate names.func MustNewNamedMap[T Named](factories ...T) NamedMap[T] {
- Parameters:
factories
-...T
: A variadic parameter representing a slice of factories that implement theNamed
interface.
- Returns:
NamedMap[T]
: The newNamedMap
instance.
- Parameters:
Get Function
-
Purpose: Retrieves a factory from the
NamedMap
by its name (string representation). Returns an error if the factory is not found or if the provided name is invalid.func (n *NamedMap[T]) Get(namestr string) (t T, err error) {
- Parameters:
namestr
-string
: The string representation of the factory name.
- Returns:
t
-T
: The factory instance, zero value if not found.err
-error
: An error if the factory is not found or the name is invalid; otherwise,nil
.
- Parameters:
Add Function
-
Purpose: Adds a factory to the
NamedMap
. Returns an error if a factory with the same name already exists.func (n *NamedMap[T]) Add(factory T) (err error) {
- Parameters:
factory
-T
: The factory instance to add.
- Returns:
err
-error
: An error if a factory with the same name already exists; otherwise,nil
.
- Parameters:
GetInOrder Function
-
Purpose: Returns the factories in the order they were added to the
NamedMap
.func (n *NamedMap[T]) GetInOrder() []T {
- Returns:
[]T
: A slice containing the factories in the order they were added.
- Returns:
Include in Getting Started: NO