dongmu1914 2019-09-14 12:54
浏览 200
已采纳

无法将函数中的变量从另一个包调用到另一个非主函数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.

  • 写回答

1条回答 默认 最新

  • duanpei4455 2019-09-14 15:40
    关注

    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
            // ...
        }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器