亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法從另一個包到另一個非主函數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 關注
  • 153 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號