小编Ley*_*ski的帖子

是什么导致了 Go 中的这个段错误?

背景:因为 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)

pointers go segmentation-fault

3
推荐指数
1
解决办法
4554
查看次数

如果我返回变量的副本而不是指针,是否需要互斥锁?

我对sync.MutexGo中的使用有点困惑.我理解基本概念(调用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)

concurrency mutex go

1
推荐指数
1
解决办法
358
查看次数

标签 统计

go ×2

concurrency ×1

mutex ×1

pointers ×1

segmentation-fault ×1