前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Go 编码建议——功能篇

Go 编码建议——功能篇

作者头像
恋喵大鲤鱼
发布2021-12-21 14:21:32
3850
发布2021-12-21 14:21:32
举报
文章被收录于专栏:C/C++基础C/C++基础

文章目录

1.枚举从 1 开始

TODO

2.使用 time 处理时间

时间处理很复杂。关于时间的错误假设通常包括以下几点:

(1)一分钟有 60 秒 (2)一小时有 60 分钟 (3)一天有 24 小时 (4)一周有七天 (5)一年 365 天

还有更多,具体可参考 Falsehoods programmers believe about time

例如,在一个时间点上加上 24 小时并不总是产生一个新的日历日。

为什么常识性的认知是错误的呢?因为地球自转的不均匀性和长期变慢性,会存在时间修正的情况,比如闰秒,闰年等。

因此,在处理时间时始终使用 “time” 包,因为它有助于以更安全、更准确的方式处理这些不正确的假设。

  • 使用 time.Time 表达瞬时时间

在处理时间的瞬间时使用 time.Time,在比较、添加或减去时间时使用 time.Time 中的方法。

代码语言:javascript
复制
// Bad
func isActive(now, start, stop int) bool {
  return start <= now && now < stop
}

// God
func isActive(now, start, stop time.Time) bool {
  return (start.Before(now) || start.Equal(now)) && now.Before(stop)
}
  • 使用 time.Duration 表达时间段
代码语言:javascript
复制
// Bad
func poll(delay int) {
  for {
    // ...
    time.Sleep(time.Duration(delay) * time.Millisecond)
  }
}
poll(10) // 是几秒钟还是几毫秒?

// Good
func poll(delay time.Duration) {
  for {
    // ...
    time.Sleep(delay)
  }
}
poll(10*time.Second) // 代码即注释
  • 对外部系统使用 time.Time 和 time.Duration

尽可能在与外部系统交互中使用 time.Durationtime.Time,例如: (1)Command-line 标志: flag 通过 time.ParseDuration 支持 time.Duration (2)JSON: encoding/json 通过其 UnmarshalJSON 方法支持将 time.Time 编码为 RFC 3339 字符串 (3)SQL: database/sql 支持将 DATETIMETIMESTAMP 列转换为 time.Time,如果底层驱动程序支持则返回 (4)YAML: gopkg.in/yaml.v2 支持将 time.Time 作为 RFC 3339 字符串,并通过 time.ParseDuration 支持 time.Duration。

当不能在这些交互中使用 time.Duration 时,请使用 intfloat64,并在字段名称中包含单位。

例如,由于 encoding/json 不支持 time.Duration,因此该单位包含在字段的名称中。

代码语言:javascript
复制
// Bad
// {"interval": 2}
type Config struct {
  Interval int `json:"interval"`
}

// Good
// {"intervalMillis": 2000}
type Config struct {
  IntervalMillis int `json:"intervalMillis"`
}

参考文献

github.com/uber-go/guide

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-12-19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 1.枚举从 1 开始
  • 2.使用 time 处理时间
  • 参考文献
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档