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

标签 go import package

我知道还有很多其他类似的问题,但它们都是关于从 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/

相关文章:

python - 在 as 之后用逗号导入

android - 使用不同的包名克隆应用程序

python - 构建 python deb 包时遇到问题,提示修改后的二进制文件

concurrency - Go 中生产者/消费者最简洁的成语是什么?

go - 创建二维 slice 时出错

dictionary - golang 内置映射和字符串键的哈希冲突?

python - Golang正则表达式可以处理类似于python的 “binary”正则表达式吗?

parsing - 导入包含混合数据类型的 CSV 文件

java - 如何修复此代码中的导入错误?

python - 如何将所有模块移动到新版本的 Python(从 3.6 到 3.7)