From 874a9220682c60a4345c165a299975a64e1be2ed Mon Sep 17 00:00:00 2001 From: Stefan Majewsky Date: Fri, 7 Nov 2025 17:12:08 +0100 Subject: [PATCH] pluggable: add Registry.TryInstantiate If we had had Option[] back when this was built, I would have Instantiate() return it directly. As it stands, we will stick with the existing interface for backwards-compatibility, but I need an Option[] return now because generic code cannot do the `if result == nil` comparison. --- pluggable/pluggable.go | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/pluggable/pluggable.go b/pluggable/pluggable.go index 120d7c4..afd0dca 100644 --- a/pluggable/pluggable.go +++ b/pluggable/pluggable.go @@ -28,7 +28,11 @@ // } package pluggable -import "fmt" +import ( + "fmt" + + . "github.com/majewsky/gg/option" +) // Plugin is the base interface for plugins that type Registry can instantiate. type Plugin interface { @@ -74,10 +78,15 @@ func (r *Registry[T]) Add(factory func() T) { // Since T is usually an application-specific interface type, this means that // nil will be returned. func (r *Registry[T]) Instantiate(pluginTypeID string) T { + var zero T + return r.TryInstantiate(pluginTypeID).UnwrapOr(zero) +} + +// TryInstantiate is like Instantiate, but returns None instead of nil for unknown plugins. +func (r *Registry[T]) TryInstantiate(pluginTypeID string) Option[T] { factory, exists := r.factories[pluginTypeID] if exists { - return factory() + return Some(factory()) } - var zero T - return zero + return None[T]() }