」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 可以在管道函數中求解1.18 \的通用類型兼容性問題嗎?

可以在管道函數中求解1.18 \的通用類型兼容性問題嗎?

發佈於2025-05-01
瀏覽:501

Can Contravariance Solve Go 1.18\'s Generic Type Compatibility Issue in the Pipe Function? 
在GO 1.18 generics

提供了轉換值的函數。它期望左功能的輸出類型與右功能的輸入類型匹配。但是,在下面的示例中,它無法編譯:

func pipe [a,t1,t2 any](左func(a)T1,right func(t1)t2)func(a)t2 { 返回func(a a)t2 { 返回右(左(a)) } } func openfile(名稱字符串) *os.file { ... } func readall(rdr io.reader)[] byte { ... } var openRead = pipe(openfile,readall)是一個錯誤?

Workaround

To address this limitation, a modified version of the Pipe function can be used, but it sacrifices compile-time type safety:

func Pipe[A, T1, T2, T3 any](left func(A) T1, right func(T2)T3)func(a)t3 { 返回func(a a)t3 { 返回右(任何(左(a))。(t2)) } }

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3