我知道还有很多其他类似的问题,但它们都是关于从 main.go 调用函数的,而我的情况不是这样。在 file1.go 中我有这样一个函数:
func (c *cubicSender) InRecovery() bool {
return c.largestAckedPacketNumber <= c.largestSentAtLastCutback && c.largestAckedPacketNumber != 0
}
func (c *cubicSender) InSlowStart() bool {
return c.GetCongestionWindow() < c.GetSlowStartThreshold()
}
我想将这些函数分配给 file2.go 中的变量 IR 和 ISS。所以当一个函数被调用时:
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")
}
我该怎么做?
*编辑:我已经导入了包,它在 file2.go 中有 file1.go。
最佳答案
InRecovery
似乎被声明为 *cubicSender
的方法,而不是函数。您不能仅通过指定声明它们的包来调用方法,您需要声明该方法的类型的实例,然后您可以通过使用实例变量的名称对其进行限定来调用该方法。
请注意,如果您想在声明它的包之外使用方法 InRecovery
,那么您需要导出方法所在的类型已定义(即 cubicSender
),或者您需要以某种方式提供对未导出类型实例的访问,例如通过导出的变量或函数。
例如在 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
}
在 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
// ...
}
}
关于go - 无法从另一个包调用函数中的变量到另一个非主函数golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57935684/