【发布时间】:2017-07-20 04:11:04
【问题描述】:
我编写了一个简单的脚本,它将读取 /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"],
}
}
正如您从代码中看到的那样,似乎没有办法使用这个变量,或者我真的错过了一些重要的点。
【问题讨论】:
-
为什么有核心图和名单?似乎您仅在 txt == 0 时附加到 cpuCores,否则将内容放入核心映射中,但在您的返回值中您仅使用 cpuCores。
标签: function loops go scope closures