Skip to main content

named.go

named.go - Overview

  1. Overview This file defines the Named interface and the NamedMap struct, which are used to manage a collection of factories that implement the Named interface. It provides methods to create, retrieve, and manage these named factories, ensuring uniqueness of names.

  2. 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 is Name.

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 to T (where T implements Named).
    • factoriesInOrder: A slice of T maintaining the insertion order.

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 the Named interface.
    • Returns:
      • NamedMap[T]: The new NamedMap instance.
      • error: An error if duplicate factory names are found; otherwise, nil.

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 the Named interface.
    • Returns:
      • NamedMap[T]: The new NamedMap instance.

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.

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.

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.

Include in Getting Started: NO