【问题标题】:Assign value to field in struct if empty如果为空,则为结构中的字段赋值
【发布时间】:2018-05-03 23:35:51
【问题描述】:

我定义了一个结构

type data struct {
  invitecode string
  fname string
  lname string
}

我在解析后从检索表单数据中填充

...

r.ParseForm()

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

我确实想检查从表单获得的invitecode 字段是否为空,如果是,则通过调用函数来填充它,但如果不是,则使用检索到的值填充它(invitecode: if newUser.invitecode == "" {"Mr"} 否则 {lnames.title},)。我知道 go 没有三元运算符,我想使用和阅读问题 herehereherehere 暗示使用 if else 语句,但我似乎无法理解工作。最好,我正在寻找一种在分配新变量时进行检查的解决方案。尝试下面的代码似乎不起作用。任何帮助将不胜感激。

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)
}

【问题讨论】:

  • 您在使用if 语句时遇到问题吗?您引用的代码中没有任何内容试图执行您所描述的操作。
  • 我更新了问题以显示我想要做什么

标签: go


【解决方案1】:

Go 没有三元组,也不能像代码中显示的那样做内联 if。你将不得不做一个普通的if 块:

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

等等。您可以将其提取到一个函数中:

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

然后像这样使用它:

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

当然,如果您处理多种类型(不仅仅是字符串),则每种类型都需要一个这样的函数。

【讨论】:

  • 谢谢,试图一次性分配所有字段,其他字段可以在 else 块中分配吗?这是一种正确的方法吗?
  • 当然,如果这是您正在寻找的行为。
【解决方案2】:

您不能像在其他语言中使用三元运算符(或 if/else 语句)那样内联使用 if ... else 语句,您必须简单地按程序执行:

user := &data{ /* ... */ }

if user.invitecode == "" {
  user.invitecode = "Mr"
} else {
  user.invitecode = lnames.title
}

【讨论】:

  • 是的,看起来 go 是为了明确而设计的,而不是为了简洁。
  • “似乎”没有,Go 是明确以这种方式设计的。该语言的开发人员在他们关于 Go 错误处理的各种博客中多次声明。他们的观点非常明确和公开,即清晰 > 简洁。
猜你喜欢
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 2020-04-10
  • 2013-10-28
  • 1970-01-01
  • 2017-10-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多