Home > OS >  Go lang - idiomatic default fallbacks
Go lang - idiomatic default fallbacks

Time:05-08

I'm fairly new to go (about 9 months now full time using Go). However, I'm used to Python, typescript and PHP and I always find a short cut with these languages. However, I'm struggling to know what would be the most idiomatic way to achieve the following:

transit := gin.H{
    "rise": rs.Rise.String(),
    "set":  rs.Set.String(),
}

if rs.Rise.IsZero() {
    transit["rise"] = nil
}

if rs.Set.IsZero() {
    transit["set"] = nil
}

Essentially, I set a default struct, then if I need to change, I change ... but it just feels inefficient to me ... so I'm wondering if there are any tricks here that I could use?

I've chosen this specific real-world scenario, but I'm happy to have examples (rather than coding for me) ...

CodePudding user response:

This is not inefficient in terms of execution. It may be a bit verbose compared to other languages. There are ways to shorten such repetitive code using anonymous functions. This can help shorten a lengthy repetitive section as you have without sacrificing readability.

type StringZeroable interface {
   fmt.Stringer
   IsZero() bool
}

checkZero:=func(in StringZeroable) interface{} {
   if in.IsZero() {
     return nil
   }
   return in.String()
}

transit := gin.H{
    "rise": checkZero(rs.Rise),
    "set":  checkZero(rs.Set)
}
  •  Tags:  
  • go
  • Related