1

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 Answer 1

7

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)

Sign up to request clarification or add additional context in comments.

2 Comments

cpu#Times returns ([]TimesStat, error) so getCpuTime() should return []cpu.TimeStat. I can't make such a small edit since its a two character insertion.
changed with comment, Thanks @algrebe!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.