Add GetStringPtr

Returns a string pointer. Returns `nil` if GetString() would have returned
`""`. If you want a pointer to the empty string, assign the string returned by
GetString and take its pointer:

```golang
v = viper.GetString("key")
ptr := &v
```
This commit is contained in:
Satya 2020-02-19 14:22:00 -08:00 committed by Satyajit Phanse
parent f2cbaea4c2
commit 4834fb6636
3 changed files with 23 additions and 1 deletions

View file

@ -507,6 +507,7 @@ The following functions and methods exist:
* `GetInt(key string) : int`
* `GetIntSlice(key string) : []int`
* `GetString(key string) : string`
* `GetStringPtr(key string) : *string`
* `GetStringMap(key string) : map[string]interface{}`
* `GetStringMapString(key string) : map[string]string`
* `GetStringSlice(key string) : []string`
@ -517,7 +518,7 @@ The following functions and methods exist:
One important thing to recognize is that each Get function will return a zero
value if its not found. To check if a given key exists, the `IsSet()` method
has been provided.
has been provided. `GetStringPtr()`, though, will return nil for empty string.
Example:
```go

View file

@ -793,6 +793,16 @@ func (v *Viper) GetString(key string) string {
return cast.ToString(v.Get(key))
}
// GetStringPt returns the value associated with the key as a string pointer, nil if it's empty string.
func GetStringPtr(key string) *string { return v.GetStringPtr(key) }
func (v *Viper) GetStringPtr(key string) *string {
s := v.GetString(key)
if s == "" {
return nil
}
return &s
}
// GetBool returns the value associated with the key as a boolean.
func GetBool(key string) bool { return v.GetBool(key) }
func (v *Viper) GetBool(key string) bool {

View file

@ -2159,3 +2159,14 @@ func BenchmarkGetBoolFromMap(b *testing.B) {
}
}
}
func TestGetStringPtr(t *testing.T) {
v := New()
v.SetConfigType("yaml")
/* config and defaults */
v.ReadConfig(bytes.NewBuffer(yamlExample))
assert.Equal(t, "leather", *v.GetStringPtr("clothing.jacket"))
assert.Nil(t, v.GetStringPtr("motorcycle"))
}