Skip to content

Commit eab3c25

Browse files
authored
Merge pull request #270 from sapcc/pluggable-tryinstantiate
pluggable: add Registry.TryInstantiate
2 parents 875cf28 + 874a922 commit eab3c25

File tree

1 file changed

+13
-4
lines changed

1 file changed

+13
-4
lines changed

pluggable/pluggable.go

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,11 @@
2828
// }
2929
package pluggable
3030

31-
import "fmt"
31+
import (
32+
"fmt"
33+
34+
. "github.com/majewsky/gg/option"
35+
)
3236

3337
// Plugin is the base interface for plugins that type Registry can instantiate.
3438
type Plugin interface {
@@ -74,10 +78,15 @@ func (r *Registry[T]) Add(factory func() T) {
7478
// Since T is usually an application-specific interface type, this means that
7579
// nil will be returned.
7680
func (r *Registry[T]) Instantiate(pluginTypeID string) T {
81+
var zero T
82+
return r.TryInstantiate(pluginTypeID).UnwrapOr(zero)
83+
}
84+
85+
// TryInstantiate is like Instantiate, but returns None instead of nil for unknown plugins.
86+
func (r *Registry[T]) TryInstantiate(pluginTypeID string) Option[T] {
7787
factory, exists := r.factories[pluginTypeID]
7888
if exists {
79-
return factory()
89+
return Some(factory())
8090
}
81-
var zero T
82-
return zero
91+
return None[T]()
8392
}

0 commit comments

Comments
 (0)