先不运行go main函数

标签 go program-entry-point process.start

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

最佳答案

specification says :

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

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

接下来是 initialization code在导入的 cpu 包中,在 main 中的任何代码之前执行。

关于先不运行go main函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46292604/

相关文章:

c# - 如何打开两个单独的(默认)浏览器窗口而不是新选项卡

c# - 在 C# 应用程序中将 2 个 .exe 捆绑在一起

interface - Go 是否允许为具有特定键类型的映射指定接口(interface)?

go - 如何将一个 slice 与其他 slice 进行比较以查看内容是否匹配

Java主类实例访问

c - 生成文件: Parameterize so that it compiles the highest numbered file

constructor - "constructors"是否有标准的惯用 Go?

inheritance - 从没有将类型转换为继承类型的继承结构执行实际对象方法

java - 错误: cant find main class