1

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)
}
mkopriva
  • 35,176
  • 4
  • 57
  • 71
driftavalii
  • 1,299
  • 1
  • 14
  • 21

2 Answers2

4

You cannot use an if ... else statement inline like you would a ternary operator (or if/else statements) in other languages, you must simply do it procedurally:

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

if user.invitecode == "" {
  user.invitecode = "Mr"
} else {
  user.invitecode = lnames.title
}
maerics
  • 151,642
  • 46
  • 269
  • 291
  • Yup, seems like go was designed for explicit clarity, not for conciseness. – maerics Nov 20 '17 at 17:31
  • 1
    No "seems" about it, Go was _explicitly_ designed in that manner. The developers of the language state it several times in their various blogs about Go error handling. Their view is very specifically and openly that clarity > conciseness. – Kaedys Nov 20 '17 at 17:45
3

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.

Adrian
  • 42,911
  • 6
  • 107
  • 99