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 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退