doumen1883 2017-11-20 17:01
浏览 122
已采纳

如果为空,则将值分配给struct中的字段

I have a struct defined

type data struct {
  invitecode string
  fname string
  lname string
}

which I populate from retrieving form data after parsing

...

r.ParseForm()

new user := &data{
  invitecode: r.FormValue("invitecode"),
  fname: r.FormValue("fname")
  lname: r.FormValue("lname")
}

I did like to check if the invitecode field obtained from the form is empty and if so, populate it by calling a function but if it is not, to populate it with the retrieved value (invitecode: if newUser.invitecode == "" {"Mr"} else {lnames.title},). I understand go doesn't have a tenary operator which I thought of using and reading the questions here, here, here & here implies using an if else statement but I can't seem to get it to work. Preferable, I am looking for a solution that check's while assigning a new variable. Trying the code below doesn't seem to work. Any help would be appreciated.

package main

import (
    "fmt"
)

type data struct {
    invitecode string
    fname      string
    lname      string
}

func main() {
    var user data

    newUser := map[string]string{"invitecode": "", "fname": "Dude", "lname": "Did"}
    user = &data{
        invitecode: if newUser.invitecode == "" {"Mr"} else {lnames.title},
        fname:      newUser.fname,
        lname:      newUser.lname,
    }
    fmt.Println(user)
}
  • 写回答

2条回答 默认 最新

  • duanba8070 2017-11-20 17:17
    关注

    Go does not have ternaries, nor can you do an inline if like you've shown in the code. You will have to do a normal if block:

    user = &data{}
    if newUser.inviteCode = "" {
        user.invitecode = "Mr"
    } else {
        user.invitecode = lnames.title
    }
    

    And so on. You could extract this into a function:

    func coalesce(args ...string) string {
        for _,str := range args {
            if str != "" {
                return str
            }
        }
        return ""
    }
    

    And use it like so:

    user.invitecode = coalesce(lnames.title, "Mr")
    

    Of course, if you deal with multiple types (not just strings), you'll need one such function for each type.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能