我寫了以下 golang 程式碼並執行了它。
type test struct { name string } func (t test) hello() { fmt.printf("hello, %s\n", t.name) } func (t *test) hello2() { fmt.printf("pointer: %s\n", t.name) } func runt(t test) { t.hello() } func main() { mapt := []test{ {name: "a"}, {name: "b"}, {name: "c"}, } for _, t := range mapt { defer t.hello() defer t.hello2() } }
輸出:
pointer: C Hello, C pointer: C Hello, B pointer: C Hello, A
我的理解是,指標 t
在 3 個循環後將指向“c”,因此三個 3“c”用於“hello2”輸出。然而,延遲“hello”函數呼叫的行為非常奇怪。看起來它正在保留它所指向的位置。 (t test)
如何影響這個?
我很好奇golang將其編譯成什麼。非常感謝!
正確答案
在 for 迴圈內,defer
語句的參數是一個閉包。閉包捕獲循環變數 t
。
對於使用值接收器的調用,閉包包含 t
的副本。對於使用指標接收器的調用,閉包包含一個指向 t
的指標。
循環變數在每次迭代時都會被重寫(此行為將在該語言的更高版本中更改)。因此,值接收器閉包捕獲每個值,而指針接收器閉包僅捕獲指針,因此,在運行時,它們使用該指針的最新值。
以上是對於同一結構體,Golang 在 for 迴圈中 defer 的行為有所不同的詳細內容。更多資訊請關注PHP中文網其他相關文章!

goisastrongchoiceforprojectsneedingsimplicity,績效和引發性,butitmaylackinadvancedfeatures and ecosystemmaturity.1)

Go'sinitfunctionandJava'sstaticinitializersbothservetosetupenvironmentsbeforethemainfunction,buttheydifferinexecutionandcontrol.Go'sinitissimpleandautomatic,suitableforbasicsetupsbutcanleadtocomplexityifoverused.Java'sstaticinitializersoffermorecontr

thecommonusecasesfortheinitfunctionoare:1)加載configurationfilesbeforeThemainProgramStarts,2)初始化的globalvariables和3)runningpre-checkSorvalidationsbeforEtheprofforeTheProgrecce.TheInitFunctionIsautefunctionIsautomentycalomationalmatomatimationalycalmatemationalcalledbebeforethemainfuniinfuninfuntuntion

ChannelsarecrucialingoforenablingsafeandefficityCommunicationBetnewengoroutines.theyfacilitateSynChronizationAndManageGoroutIneLifeCycle,EssentialforConcurrentProgramming.ChannelSallSallSallSallSallowSallowsAllowsEnderDendingAndReceivingValues,ActassignalsignalsforsynChronization,and actassignalsynChronization and andsupppor

在Go中,可以通過errors.Wrap和errors.Unwrap方法來包裝錯誤並添加上下文。 1)使用errors包的新功能,可以在錯誤傳播過程中添加上下文信息。 2)通過fmt.Errorf和%w包裝錯誤,幫助定位問題。 3)自定義錯誤類型可以創建更具語義化的錯誤,增強錯誤處理的表達能力。

Gooffersrobustfeaturesforsecurecoding,butdevelopersmustimplementsecuritybestpracticeseffectively.1)UseGo'scryptopackageforsecuredatahandling.2)Manageconcurrencywithsynchronizationprimitivestopreventraceconditions.3)SanitizeexternalinputstoavoidSQLinj

Go的錯誤接口定義為typeerrorinterface{Error()string},允許任何實現Error()方法的類型被視為錯誤。使用步驟如下:1.基本檢查和記錄錯誤,例如iferr!=nil{log.Printf("Anerroroccurred:%v",err)return}。 2.創建自定義錯誤類型以提供更多信息,如typeMyErrorstruct{MsgstringDetailstring}。 3.使用錯誤包裝(自Go1.13起)來添加上下文而不丟失原始錯誤信息,

對效率的Handleerrorsinconcurrentgopragrs,UsechannelstocommunicateErrors,enplionErrorWatchers,Instertimeout,UsebufferedChannels和Provideclearrormessages.1)USEchannelelStopassErtopassErrorsErtopassErrorsErrorsErrorsFromGoroutInestOthemainFunction.2)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

禪工作室 13.0.1
強大的PHP整合開發環境

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3漢化版
中文版,非常好用

Atom編輯器mac版下載
最受歡迎的的開源編輯器