Basic retrieval functions are used to retrieve a single element from the injector.
Get
Get returns the element and an error. Use this when you need to handle errors explicitly.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
packagemainimport("database/sql""log""github.com/wrapped-owls/goremy-di/remy")funcmain(){db,err:=remy.Get[*sql.DB](injector)iferr!=nil{log.Fatal(err)}// Use db...}
MustGet
MustGet returns the element and panics if an error occurs. Use when you’re certain the element exists.
1
2
3
4
5
6
7
8
9
10
11
12
packagemainimport("database/sql""github.com/wrapped-owls/goremy-di/remy")funcmain(){db:=remy.MustGet[*sql.DB](injector)// Use db... (will panic if not found)}
MaybeGet
MaybeGet returns the element or the zero value if an error occurs. Use when you want to ignore errors gracefully.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
packagemainimport("database/sql""github.com/wrapped-owls/goremy-di/remy")funcmain(){db:=remy.MaybeGet[*sql.DB](injector)// db will be nil if not found, but no error handling neededifdb!=nil{// Use db...}}
Retrieving Multiple Matches
When you expect multiple registered elements to match the same requested type (for example, several implementations of
an interface while duck typing is enabled), use the GetAll family:
GetAll[T] returns ([]T, error)
MustGetAll[T] panics on error
MaybeGetAll[T] returns an empty slice on error
1
2
3
4
5
6
7
// Example: retrieve all encoders implementing the same interfacetypeEncoderinterface{Encode([]byte)[]byte}encoders:=remy.MustGetAll[Encoder](injector)for_,enc:=rangeencoders{_=enc.Encode([]byte("payload"))}
If you only need one specific implementation among many, prefer registering and retrieving with tags to disambiguate.