function - 无法使用范围使用变量

标签 function loops go scope closures

我写了一个简单的脚本,它将读取/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"],
    }
}

正如您从代码中看到的那样,似乎没有办法使用这个变量,或者我真的遗漏了一些重要的要点。

最佳答案

看起来你想做这样的事情:

struct CpuCore {
    VendorID string
    ModelName string
}

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(CpuCore, 0)
    for s.Scan() {
        txt := s.Text()

        fields := strings.Split(txt, ":")

        if len(fields) < 2 {
            continue
        }

        var k, v = strings.TrimSpace(fields[0]), strings.TrimSpace(fields[1])
        cpuCores = append(cpuCores, CpuCores{VendorID: k, ModelName: v})
    }
    return CpuInfo{
        Cores:    cpuCores,
        CpuCount: uint(runtime.NumCPU()),
        Brand:    cpuCores[0].VendorID,
        Model:    cpuCores[0].ModelName,
    }
}

我假设您有一个结构 CpuCore 并且您想要创建一个名为 cpuCores 的数组。

如果您包含更多代码和类型,我们可能会真正尝试运行此代码。

关于function - 无法使用范围使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42521462/

相关文章:

在 C 的 typedef 结构中调用函数

javascript - 基本事件监听器抛出错误 ('undefined is not a function' )

reflection - Go:我怎样才能 "unpack"一个结构?

gorename : What is a 'DO NOT EDIT' marker?

json - 将不断变化的类型流解码为结构

swift 5 : Wrong change tag when send a function to GestureRecognizer

function - 过程指针不能指向基本函数

loops - 我应该使用 cfobject 还是 cfinvoke 来完成重复性任务?

c - 循环不完整

ruby-on-rails - 如何在 Rails View 中循环并打印多维数组?