Home > Software design >  How to make multiple if-conditions efficiently in Go?
How to make multiple if-conditions efficiently in Go?

Time:02-04

I have to check a set of variables, if they contain an empty string as value. If the string is empty, it should be set to a default value of "no value". What is a efficient way to handle this in Golang?

Example given:

func defaultValue (myObject) {
    if myObject.name == "" {
        myObject.name = "no value"
    }
    if myObject.color == "" {
        myObject.color = "no value"
    }
    if myObject.typing == "" {
        myObject.typing = "no value"
    }
    if myObject.price == "" {
        myObject.price = "no value"
    }
}

I know how to do it with simple if statements, but I am wondering if there is an approach more efficient to this.

CodePudding user response:

You can create a separate function for that

func optional(input string) string {
   if input == "" {
       return "no value"
   }
   return input
}

func defaultValue (myObject) {
    myObject.name = optional(myObject.name)
    myObject.color = optional(myObject.color)
    myObject.typing = optional(myObject.typing)
    myObject.price = optional(myObject.price)
}

CodePudding user response:

func aorb[T comparable](a, b T) T {
    var z T
    if a != z {
        return a
    }
    return b
}
func defaultValue(o *myObject) {
    o.name = aorb(o.name, "no value")
    o.color = aorb(o.color, "no value")
    o.typing = aorb(o.typing, "no value")
    o.price = aorb(o.price, "no value")
}

CodePudding user response:

You can create a generic helper that checks a specific field. If you pass the address of the field, the helper can also set the default value. Using variadic argument you can even list multiple fields (if they should have the same default value):

func check[T comparable](def T, fields ...*T) {
    var zero T
    for _, field := range fields {
        if *field == zero {
            *field = def
        }
    }
}

Testing it:

type Obj struct {
    name, color, typing, price string
}

func main() {
    o := Obj{color: "red"}
    fmt.Printf("%#v\n", o)
    check("no value", &o.name, &o.color, &o.typing, &o.price)
    fmt.Printf("%#v\n", o)
}

This will output (try it on the Go Playground):

main.Obj{name:"", color:"red", typing:"", price:""}
main.Obj{name:"no value", color:"red", typing:"no value", price:"no value"}
  • Related