为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
隔江千里 2023-07-26 10:08:07
我知道还有很多类似的问题,但它们都是关于从 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。
查看完整描述

1 回答

?
天涯尽头无女友

TA贡献1831条经验 获得超9个赞

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

        // ...

    }


}


查看完整回答
反对 回复 2023-07-26
  • 1 回答
  • 0 关注
  • 74 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信