背景:因为 Go 的内置 JSON 编组器在给定omitempty
标志时不会检查零值,所以我们正在尝试使用*time.Time
而不是time.Time
在需要干净地编组为 JSON 的结构中使用。这个问题显然是我们需要非常小心,在使用它时总是检查它是否为空。我们注意到的一件事是在包含结构体上设置创建时间的函数中,当我们检查数据库中的 JSON 时,所有时间都完全相同,精确到纳秒。
为了检查这是否与指针有关,还是仅仅因为系统运行良好,我进行了以下测试:
package main
import (
"fmt"
"time"
)
type Timekeeper struct {
myTime *time.Time
}
func main() {
t := make([]Timekeeper, 100)
var now time.Time
for _, v := range t {
now = time.Now()
v.myTime = &now
time.Sleep(1 * time.Second)
}
for i, times := range t {
fmt.Printf("Timekeeper %s time: %s.", i, times.myTime.Format(time.RFC3339Nano))
}
}
Run Code Online (Sandbox Code Playgroud)
但它不断产生这种恐慌:
panic: runtime error: invalid …
Run Code Online (Sandbox Code Playgroud) 我对sync.Mutex
Go中的使用有点困惑.我理解基本概念(调用Lock()
会阻止其他goroutine在它之间执行代码Unlock()
),但我不确定我是否需要它.我已经看到了相当多的C++答案,但在每个例子中,他们似乎都在直接修改和访问变量.
这是我的一个名为configuration的包中的代码,我将在整个应用程序中使用它来获取(令人惊讶的)配置和设置信息.
package config
import (
"encoding/json"
"fmt"
"os"
"sync"
log "github.com/sirupsen/logrus"
)
/*
ConfigurationError is an implementation of the error interface describing errors that occurred while dealing with this
package.
*/
type ConfigurationError string
/*
Error prints the error message for this ConfigurationError. It also implements the error interface.
*/
func (ce ConfigurationError) Error() string {
return fmt.Sprintf("Configuration error: %s", string(ce))
}
/*
configuration is a data struct that holds all …
Run Code Online (Sandbox Code Playgroud)