Skip to content

Commit

Permalink
Support []any
Browse files Browse the repository at this point in the history
  • Loading branch information
chriso committed Jun 28, 2024
1 parent 47102ce commit beb6bd0
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
12 changes: 10 additions & 2 deletions dispatchproto/any.go
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,10 @@ func newStructpbValue(rv reflect.Value) (*structpb.Value, error) {
return structpb.NewNumberValue(rv.Float()), nil
case reflect.String:
return structpb.NewStringValue(rv.String()), nil
case reflect.Interface:
if rv.NumMethod() == 0 { // interface{} aka. any
return newStructpbValue(reflect.ValueOf(rv.Interface()))
}
case reflect.Slice:
list := &structpb.ListValue{Values: make([]*structpb.Value, rv.Len())}
for i := range list.Values {
Expand All @@ -446,9 +450,8 @@ func newStructpbValue(rv reflect.Value) (*structpb.Value, error) {
}
}
return structpb.NewListValue(list), nil
default:
return nil, fmt.Errorf("not implemented: %s", rv.Type())
}
return nil, fmt.Errorf("not implemented: %s", rv.Type())
}

func fromStructpbValue(rv reflect.Value, s *structpb.Value) error {
Expand Down Expand Up @@ -490,6 +493,11 @@ func fromStructpbValue(rv reflect.Value, s *structpb.Value) error {
}
return nil
}
case reflect.Interface:
if rv.NumMethod() == 0 { // interface{} aka. any
rv.Set(reflect.ValueOf(s.AsInterface()))
return nil
}
}
return fmt.Errorf("cannot deserialize %T into %v (%v kind)", s, rv.Type(), rv.Kind())
}
1 change: 1 addition & 0 deletions dispatchproto/any_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,7 @@ func TestAny(t *testing.T) {
[]bool{true, false, true},
[]float64{3.14, 1.25},
[][]string{{"foo", "bar"}, {"abc", "xyz"}},
[]any{3.14, true, "x"},
} {
t.Run(fmt.Sprintf("%v", v), func(t *testing.T) {
boxed, err := dispatchproto.Marshal(v)
Expand Down

0 comments on commit beb6bd0

Please sign in to comment.