diff --git a/candid/idl/encode_test.go b/candid/idl/encode_test.go index 42bae16..c9ab00d 100644 --- a/candid/idl/encode_test.go +++ b/candid/idl/encode_test.go @@ -31,3 +31,20 @@ func TestEncode_issue7(t *testing.T) { t.Fatal(err) } } + +func TestVariantType_default(t *testing.T) { + type V = struct { + A *Null `ic:"A,variant"` + B *Null `ic:"B,variant"` + } + raw, err := Marshal([]any{ + V{}, + }) + if err == nil { + t.Error("expected error") + } + var v V + if err := Unmarshal(raw, []any{&v}); err == nil { + t.Error("expected error") + } +} diff --git a/candid/idl/variant.go b/candid/idl/variant.go index 666b6cd..ad7374d 100644 --- a/candid/idl/variant.go +++ b/candid/idl/variant.go @@ -136,7 +136,7 @@ func (variant VariantType) EncodeValue(value any) ([]byte, error) { return concat(id, v_), nil } } - return nil, fmt.Errorf("unknown variant: %variant", value) + return nil, fmt.Errorf("unknown variant: %v", value) } func (variant VariantType) String() string { @@ -220,10 +220,7 @@ func (variant VariantType) structToVariant(value any) (*Variant, error) { }, nil } if i == v.NumField()-1 { - return &Variant{ - Name: tag.Name, - Value: nil, - }, nil + return nil, fmt.Errorf("invalid variant: no variant selected") } } return nil, fmt.Errorf("invalid variant: %s", v.Type())