登录
首页 >  Golang >  Go问答

使用结构体更新值

来源:stackoverflow

时间:2024-04-01 11:27:35 137浏览 收藏

一分耕耘,一分收获!既然打开了这篇文章《使用结构体更新值》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!

问题内容

当我更新结构体中的空字符串值以更新 dynamodb 表时,我陷入困境。

目前我有这个结构

type client struct {
    clientid       *string    `json:"client_key,omitempty"`
    name           *string    `json:"client_name,omitempty"`
    address        *string    `json:"address,omitempty"`
    country        *string    `json:"country,omitempty"`
    city           *string    `json:"city,omitempty"`
    state          *string    `json:"state,omitempty"`
    postcode       *string    `json:"post_code,omitempty"`
    createdat      *time.time `json:"created_at,omitempty"`
}

更新项目时的代码

keyattr, err := dynamodbattribute.marshalmap(key)
if err != nil {
    return nil, err
}
valattr, err := dynamodbattribute.marshalmap(attributes)
if err != nil {
    return nil, err
}

keyattr 将用于 key 字段,valattr 将用于 expressionattributevalues 字段。请注意,为了节省空间,我没有包含完整的更新字段函数。但如果你要求的话我会这么做。

目前,该函数运行良好,除非我用空字符串更新了其中一个字段。例如。 client.address = aws.string("").虽然我可以使用 dynamodb 将空字符串转换为 null,但由于 omitempty 标签,我似乎找不到更新它的方法。

我需要 omitempty 标记来忽略所有 nil 值。但是,我刚刚研究发现 omitempty 标签也省略了空字符串值。目前我必须在我的函数中创建一个像这样的结构。

type client struct {
    Name     *string `json:"client_name"`
    Address  *string `json:"address"`
    Country  *string `json:"country"`
    City     *string `json:"city"`
    State    *string `json:"state"`
    PostCode *string `json:"post_code"`
}

但我不喜欢重复事情。那么,问题是:有没有更好的方法来做到这一点?你们如何在 dynamodb 中使用结构体?

编辑

根据@peter的评论,似乎 json.encode() 确实会打印空字符串(如果它不为零)。

{"client_key":"test","用户名":"test","电子邮件":"","first_name":"test","last_name":"","电话":"", "标题":"","email_verified":false,"phone_verified":false,"updated_at":"2018-12-06t14:04:56.2743841+11:00"}

问题似乎出在 dynamodbattribute.marshalmap 函数


解决方案


经过多次尝试,终于搞定了。我没有测试过,所以不知道是否有bug。但它现在似乎对我有用。

所以我所做的是首先使用 json.marshal 对结构进行编码,然后使用 json.unmarshalmap[string]interface{}。然后,我使用 dynamodbattribute.marshal 将其转换为 map[string]*attributevalue

代码如下:

var temp map[string]interface{}
json.Unmarshal(tempStr, &temp)
valAttr, err := dynamodbattribute.MarshalMap(temp)
if err != nil {
    return nil, err
}

到这里,我们也就讲完了《使用结构体更新值》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>