Go语言 – 惯用的默认回退机制

huangapple go评论71阅读模式
英文:

Go lang - idiomatic default fallbacks

问题

我对Go语言还比较新(全职使用Go已经有9个月了)。然而,我习惯于Python、TypeScript和PHP,并且我总是能在这些语言中找到捷径。然而,我不知道在Go语言中如何以最符合惯用法的方式实现以下功能:

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
}

基本上,我设置了一个默认的结构体,然后如果需要更改,我就进行更改...但是这种方式对我来说感觉效率不高...所以我想知道是否有任何技巧可以在这里使用?

我选择了这个具体的实际场景,但我很乐意提供示例(而不是为我编码)...

英文:

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

答案1

得分: 3

这在执行方面并不低效。与其他语言相比,它可能有点啰嗦。使用匿名函数可以缩短这种重复的代码,这有助于缩短冗长的重复部分,同时不影响可读性。

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)
}
英文:

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

huangapple
  • 本文由 发表于 2022年5月7日 20:47:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/72152656.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定