主函数未首先执行

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

Go main function not operated first

问题

package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
"strings"
"unicode/utf8"
"sync"
"github.com/robfig/cron"
cpu "github.com/shirou/gopsutil/cpu"
"fmt"
)

const NumofResource = 4

// 结构体
type HostInfo struct {
Hostid string
}

var c *cron.Cron
var lastCPUTimes []cpu.TimesStat

func main() {
fmt.Println("1.main.go > main() start")
defer l4g.Close()

var err interface{}
lastCPUTimes, err = cpu.Times(false) //nil
fmt.Println("2.main.go > err", err)
fmt.Println("3.main.go > lastCPUTimes", lastCPUTimes)

if err != nil {
l4g.Error(err)
}
}

我知道main函数首先被执行。
然而,我们确认了名为cpu_windows.go的库首先被执行。
为什么?

cpu_windows.go: Times(bool) false

cpu_windows.go: common.ProcGetSystemTimes.Call 1

cpu_windows.go: Times(bool) true

cpu_windows.go: return perCPUTimes()

1.main.go: main() start

cpu_windows.go: Times(bool) false

cpu_windows.go: common.ProcGetSystemTimes.Call 1

2.main.go: err

英文:
package main
import (
    "bytes"
    "encoding/json"
    "io/ioutil"
    "log"
    "net/http"
    "os"
    "os/signal"
    "strings"
    "unicode/utf8"
    "sync"
    "github.com/robfig/cron"
     cpu "github.com/shirou/gopsutil/cpu"
    "fmt"
)

const NumofResource = 4

// 구조체
type HostInfo struct {
    Hostid string
}

var c *cron.Cron
var lastCPUTimes []cpu.TimesStat

func main() {
    fmt.Println("1.main.go > main() start")
    defer l4g.Close()

var err interface{}
lastCPUTimes, err = cpu.Times(false) //nil
fmt.Println("2.main.go > err", err)
fmt.Println("3.main.go > lastCPUTimes", lastCPUTimes)

if err != nil {
    l4g.Error(err)
}
}

I know that the main function is executed first.
However, we confirmed that the library called cpu_windows.go is executed first.
Why?

> cpu_windows.go : Times(bool) false
>
> cpu_windows.go : common.ProcGetSystemTimes.Call 1
>
> cpu_windows.go : Times(bool) true
>
> cpu_windows.go : return perCPUTimes()
>
> 1.main.go : main() start
>
> cpu_windows.go : Times(bool) false
>
> cpu_windows.go : common.ProcGetSystemTimes.Call 1
>
> 2.main.go : err <nil>

答案1

得分: 1

根据规范

> 如果一个包有导入,那么在初始化该包本身之前,导入的包会被初始化。

并且

> 程序的执行从初始化主包开始,然后调用 main 函数。

由此可见,在导入的 cpu 包中的初始化代码会在 main 中的任何代码之前执行。

英文:

The specification says:

> If a package has imports, the imported packages are initialized before initializing the package itself.

and

> Program execution begins by initializing the main package and then invoking the function main.

It follows that the initialization code in the imported cpu package is executed before any code in main.

huangapple
  • 本文由 发表于 2017年9月19日 13:37:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/46292604.html
匿名

发表评论

匿名网友

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

确定