我在go中具有以下PartnerType
“enum”结构:
// PartnerType enum
type PartnerType int
const (
// PartnerTypeUnknown should never happen
PartnerTypeUnknown PartnerType = iota
// PartnerTypeTest test
PartnerTypeTest
)
func (t PartnerType) String() string {
names := [...]string{
"UNKNOWN",
"TEST"}
if t < PartnerTypeUnknown || t > PartnerTypeTest {
return names[0]
}
return names[t]
}
// MarshalJSON for enum
func (t PartnerType) MarshalJSON() ([]byte, error) {
s := t.String()
return json.Marshal(s)
}
// UnmarshalJSON for enum
func (t *PartnerType) UnmarshalJSON(b []byte) error {
*t = PartnerTypeUnknown
return nil
}
// MarshalText implements the text marshaller method
func (t *PartnerType) MarshalText() ([]byte, error) {
return []byte(t.String()), nil
}
// UnmarshalText implements the text unmarshaller method
func (t *PartnerType) UnmarshalText(text []byte) error {
*t = PartnerTypeUnknown
return nil
}
// Partner entity
type Partner struct {
ID string `dynamodbav:"PK,omitempty"`
Foo string `dynamodbav:"SK,omitempty"`
PartnerType PartnerType `dynamodbav:",omitempty,string"`
}
在执行
dynamodbattribute.MarshalMap()
时,我希望将PartnerType
存储为字符串。 dynamodbav struct标记允许您将int作为字符串(dynamodbav:",omitempty,string"
)存储,但是它没有调用我定义的.String()
或Marshal/Unmarshal
实现。换句话说,它将
PartnerTypeTest
存储为"1"
而不是"TEST"
。如何才能做到这一点?
最佳答案
对于dynamodb,您可以为枚举实现marshaler/unmarshaler
请尝试以下操作:
// MarshalDynamoDBAttributeValue for ddb
func (t PartnerType) MarshalDynamoDBAttributeValue(av *dynamodb.AttributeValue) error {
s := t.String()
av.S = &s
return nil
}
// UnmarshalDynamoDBAttributeValue implements the Unmarshaler interface
func (t *PartnerType) UnmarshalDynamoDBAttributeValue(av *dynamodb.AttributeValue) error {
// val := aws.StringValue(av.S)
*t = PartnerTypeUnknown
return nil
}