我在 go 中有以下PartnerType“enum”結(jié)構(gòu):// PartnerType enumtype PartnerType intconst ( // 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 enumfunc (t PartnerType) MarshalJSON() ([]byte, error) { s := t.String() return json.Marshal(s)}// UnmarshalJSON for enumfunc (t *PartnerType) UnmarshalJSON(b []byte) error { *t = PartnerTypeUnknown return nil}// MarshalText implements the text marshaller methodfunc (t *PartnerType) MarshalText() ([]byte, error) { return []byte(t.String()), nil}// UnmarshalText implements the text unmarshaller methodfunc (t *PartnerType) UnmarshalText(text []byte) error { *t = PartnerTypeUnknown return nil}// Partner entitytype Partner struct { ID string `dynamodbav:"PK,omitempty"` Foo string `dynamodbav:"SK,omitempty"` PartnerType PartnerType `dynamodbav:",omitempty,string"`}在執(zhí)行 a 時(shí),dynamodbattribute.MarshalMap()我希望PartnerType將 my 存儲(chǔ)為字符串。dynamodbav結(jié)構(gòu)標(biāo)記允許您將 int 存儲(chǔ)為字符串 ( ) ,dynamodbav:",omitempty,string"但它不會(huì)調(diào)用我定義的.String()或Marshal/Unmarshal實(shí)現(xiàn)。換句話說(shuō),它存儲(chǔ)PartnerTypeTest為"1"not "TEST"。如何才能做到這一點(diǎn)?
1 回答

四季花海
TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超5個(gè)贊
對(duì)于 dynamodb,您可以為枚舉實(shí)現(xiàn)編組器/解組器
請(qǐng)嘗試以下操作:
// 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
}
- 1 回答
- 0 關(guān)注
- 179 瀏覽
添加回答
舉報(bào)
0/150
提交
取消