我已经写了一个简单的脚本,将读取/ proc/cpuinfo并返回一个[]map[string]string
包含关于核心的信息。有没有办法使用范围
问题是我无法使用范围内的值,它总是给我最后一个CPU的信息。
我尝试使用闭合字面无处不在。而且我试图在循环中本地复制变量,但仍然没有成功。
这里是我的代码
func GetCpuInfo() CpuInfo {
cpus, err := os.Open("/proc/cpuinfo")
if err != nil {
log.Fatalln("Cannot open /proc/cpuinfo")
}
defer cpus.Close()
s := bufio.NewScanner(cpus)
cpuCores := make(CpuCores, 0)
core := map[string]string{}
for s.Scan() {
txt := s.Text()
//copying the variable also does not work
core := core
if len(txt) == 0 {
//tried to use closure here with no success
cpuCores = append(cpuCores, core)
continue
}
fields := strings.Split(txt, ":")
if len(fields) < 2 {
continue
}
//using closure here wont work either
var k, v = strings.TrimSpace(fields[0]), strings.TrimSpace(fields[1])
core[k] = v
}
return CpuInfo{
Cores: cpuCores,
CpuCount: uint(runtime.NumCPU()),
Brand: cpuCores[0]["vendor_id"],
Model: cpuCores[0]["model name"],
}
}
正如你看到的代码看起来有没有办法使用这个变量还是我真的错过了一些巨大的点。
为什么你有核心的地图和列表?好像你只追加到cpuCores当TXT == 0否则就把事情的核心地图,在你的返回值只使用cpuCores。 – stderr