Allow the any type to be set to nil in `convert.FromTyped` (#1518)

## Changes

This came up in integration testing for #1511. One of the tests
converted a `map[string]any` to a dynamic value and encountered a `nil`
and errored out. We can safely return a nil in this case.

## Tests

Unit test passes.
This commit is contained in:
Pieter Noordhuis 2024-06-21 13:19:48 +02:00 committed by GitHub
parent 01adef666a
commit 87bc583819
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 11 additions and 0 deletions

View File

@ -72,6 +72,9 @@ func fromTyped(src any, ref dyn.Value, options ...fromTypedOptions) (dyn.Value,
return fromTypedInt(srcv, ref, options...) return fromTypedInt(srcv, ref, options...)
case reflect.Float32, reflect.Float64: case reflect.Float32, reflect.Float64:
return fromTypedFloat(srcv, ref, options...) return fromTypedFloat(srcv, ref, options...)
case reflect.Invalid:
// If the value is untyped and not set (e.g. any type with nil value), we return nil.
return dyn.NilValue, nil
} }
return dyn.InvalidValue, fmt.Errorf("unsupported type: %s", srcv.Kind()) return dyn.InvalidValue, fmt.Errorf("unsupported type: %s", srcv.Kind())

View File

@ -619,3 +619,11 @@ func TestFromTypedFloatTypeError(t *testing.T) {
_, err := FromTyped(src, ref) _, err := FromTyped(src, ref)
require.Error(t, err) require.Error(t, err)
} }
func TestFromTypedAnyNil(t *testing.T) {
var src any = nil
var ref = dyn.NilValue
nv, err := FromTyped(src, ref)
require.NoError(t, err)
assert.Equal(t, dyn.NilValue, nv)
}