无法将函数中的变量从另一个包调用到另一个非主函数golang

问题描述:

I know there are lots of other questions like this but they are all about calling a function from a main.go, which is not my case. In file1.go I have a function like this:

func (c *cubicSender) InRecovery() bool {
    return c.largestAckedPacketNumber <= c.largestSentAtLastCutback && c.largestAckedPacketNumber != 0
}

func (c *cubicSender) InSlowStart() bool {
    return c.GetCongestionWindow() < c.GetSlowStartThreshold()
}

I want to assign these functions into variables IR and ISS in file2.go. So when a function is called:

if IR == true {
            fmt.Println(pathID, pth.sentPacketHandler.GetCongestionWindow(), pth.sentPacketHandler.GetBytesInFlight(), pth.rttStats.SmoothedRTT(), time.Now().UnixNano(), "SS")
} else if ISS == true {
            fmt.Println(pathID, pth.sentPacketHandler.GetCongestionWindow(), pth.sentPacketHandler.GetBytesInFlight(), pth.rttStats.SmoothedRTT(), time.Now().UnixNano(), "IR")
}

How can I do that?

*Edit: I have imported the package, which has file1.go in file2.go.

InRecovery seems to be declared as a method of *cubicSender, not as a function. You cannot call methods just by specifying the package in which they are declared, you need an instance of the type on which the method is declared and then you can call the method by qualifying it with the instance variable's name.

Note that if you want to use the method InRecovery outside of the package in which it is declared, then you need to either export the type on which the method is defined (i.e. cubicSender), or you need to somehow provide access to an instance of the unexported type, e.g. via an exported variable, or function.

For example in congestion/file1.go:

package congestion

type cubicSender struct {
    // ...
}

// exported function to provide access to the unexported type
func NewCubicSender() *cubicSender {
    return &cubicSender{
        // ...
    }
}

func (c *cubicSender) InRecovery() bool {
    return false
}

And in quic/file2.go:

package quic

import "path/to/congestion"

func foobar() {

    c := congestion.NewCubicSender() // initialize an instance of cubicSender
    if c.InRecovery() { // call InRecovery on the instance
        // ...
    }

}