Returning a struct in Golang

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

Returning a struct in Golang

问题

我刚开始学习Golang,对于与其他包的交互和使用结构体感到非常困惑。我现在只是尝试返回由gopsutil库中的一个方法生成的结构体。具体来说,我想返回以下函数的结果:链接描述

我写的代码如下:

package main

import (
    "fmt"
    "github.com/shirou/gopsutil/cpu"
)

func main() {
    cpuTimes := getCpuTime()
    fmt.Println(cpuTimes)
}

func getCpuTime() cpu.TimesStat {
    ct, _ := cpu.Times(false)
    return ct
}

这会返回TimesStat未定义的错误。我尝试了几种不同的语法变化,但是我发现唯一能编译通过的返回值是interface{},这会得到带有方括号的结构体(例如[{values...}]),而且还会导致其他问题。我似乎找不到任何我想做的事情的示例。感谢任何帮助。

英文:

I'm just starting with Golang and I am very confused about interacting with other packages and using structs. Right now I am simply trying to return the a struct generated by a method in the gopsutil library. Specifically the return of the following function: enter link description here

My code for this is the following:

package main

import (
    "fmt"

    "github.com/shirou/gopsutil/cpu"

)

func main() {

    cpu_times = getCpuTime()
    fmt.Println(cpu_times)

}

func getCpuTime() TimesStat {
    ct, _ := cpu.Times(false)

    return ct
}

This returns TimesStat as undefined. I tried returning a few different syntactical variations, however the only return value I have found that compiles is interface{}, which gets me the struct inside of brackets (eg [{values...}]) and that led to some other problems. I can't seem to find any examples of what I am trying to do. Any help appreciated thanks.

1: https://godoc.org/github.com/shirou/gopsutil/cpu#Times "godoc link"

答案1

得分: 7

你需要在类型之前包含包名,像这样:

func getCpuTime() []cpu.TimesStat { // 在类型之前加上包名
    ct, _ := cpu.Times(false)

    return ct
}

由于这是一个 cpu.TimesStat 的切片,你可能想在调用函数中添加一个索引,或者将函数更改为只返回单个 cpu.TimesStat。(感谢 @algrebre)

英文:

you need to include the package name before the type, like so:

func getCpuTime() []cpu.TimesStat { // with package name before type
    ct, _ := cpu.Times(false)

    return ct
}

since that is a slice of cpu.TimesStat, you probably want to add an index in the calling function or change the function to just return a single cpu.TimesStat. (thanks to @algrebre)

huangapple
  • 本文由 发表于 2016年9月14日 20:50:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/39490907.html
匿名

发表评论

匿名网友

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

确定