gpt4 book ai didi

go - 将类型 *string 转换为类型 bson.ObjectId

转载 作者:IT王子 更新时间:2023-10-29 01:43:54 27 4
gpt4 key购买 nike

我需要将类型字符串转换为 bson.ObjectId,这是我当前的代码:

type CampaignUpdateBody struct {
CampaignName *string `json:"campaign_name" bson:"campaign_name"`
FromName []string `json:"from_name" bson:"from_name"`
FromEmail *string `json:"from_email" bson:"from_email"`
ReplyEmail *string `json:"reply_email" bson:"reply_email"`
Subject []string `json:"subject" bson:"subject"`
BodyText *string `json:"body_text" bson:"body_text"`
BodyHTML *string `json:"body_html" bson:"body_html"`
SmtpList *string `json:"smtp_list_id" bson:"smtp_list"`
EmailList *string `json:"email_list_id" bson:"email_list"`
}

// LetterTemplateUpdate updates some fields of the letter template.
func (s *Service) CampaignUpdate(c *gin.Context) {
id := bson.ObjectIdHex(c.Param("id"))
if !id.Valid() {
c.JSON(http.StatusBadRequest, gin.H{"error": "id has wrong format"})
return
}

var body CampaignUpdateBody
if err := c.BindJSON(&body); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
token := c.MustGet(tokenKey).(*models.Token)

params := storage.CampaignUpdateParams{}
params.ID = id
//..........................
params.BodyText = body.BodyText
params.BodyHTML = body.BodyHTML
params.SmtpList = body.SmtpList
params.EmailList = body.EmailList

stor := c.MustGet(storageKey).(storage.Storage)
if err := stor.CampaignUpdate(token.UserID, params); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{})
}

这是我当前的错误:

..\httpservice\campaigns.go:134:19: cannot use body.SmtpList (type *string) as t
ype bson.ObjectId in assignment
..\httpservice\campaigns.go:135:19: cannot use body.EmailList (type *string) as
type bson.ObjectId in assignment

我需要将 body.SmtpList 类型转换为 bson.ObjectId 中的 *string,我该怎么做?

最佳答案

根据文档,bson.ObjectId 定义为

type ObjectId string

鉴于此,您应该能够使用

params.SmtpList = bson.ObjectId(*body.SmtpList)

这是一种类型转换,它之所以有效,是因为 ObjectId 的基础类型是 string

请注意,在执行此操作之前,您需要确保 body.SmtpList 不是 nil,否则您的代码会出现 panic。

关于go - 将类型 *string 转换为类型 bson.ObjectId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54384053/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com