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

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

Go lang - idiomatic default fallbacks

问题

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

  1. transit := gin.H{
  2. "rise": rs.Rise.String(),
  3. "set": rs.Set.String(),
  4. }
  5. if rs.Rise.IsZero() {
  6. transit["rise"] = nil
  7. }
  8. if rs.Set.IsZero() {
  9. transit["set"] = nil
  10. }

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

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

英文:

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:

  1. transit := gin.H{
  2. "rise": rs.Rise.String(),
  3. "set": rs.Set.String(),
  4. }
  5. if rs.Rise.IsZero() {
  6. transit["rise"] = nil
  7. }
  8. if rs.Set.IsZero() {
  9. transit["set"] = nil
  10. }

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

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

  1. type StringZeroable interface {
  2. fmt.Stringer
  3. IsZero() bool
  4. }
  5. checkZero := func(in StringZeroable) interface{} {
  6. if in.IsZero() {
  7. return nil
  8. }
  9. return in.String()
  10. }
  11. transit := gin.H{
  12. "rise": checkZero(rs.Rise),
  13. "set": checkZero(rs.Set)
  14. }
英文:

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.

  1. type StringZeroable interface {
  2. fmt.Stringer
  3. IsZero() bool
  4. }
  5. checkZero:=func(in StringZeroable) interface{} {
  6. if in.IsZero() {
  7. return nil
  8. }
  9. return in.String()
  10. }
  11. transit := gin.H{
  12. "rise": checkZero(rs.Rise),
  13. "set": checkZero(rs.Set)
  14. }

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:

确定