👩💻 Join our community of thousands of amazing developers!
淺談Golang Generic 泛型 什麼是泛型? 泛型(Generic)是一種用來協助製作通用function、struct用的功能。 在泛型還沒有支援之前,要製作通用的function、stuct,通常就只能在輸入、輸出的地方使用interface{}結構。 而且這樣做需要很小心的檢查使用是的形態是否正確。 在function參數上使用泛型 在使用泛型之前,我們會使用interface{}來製作通用function 例如: func Add(a, b interface{}) interface{}{ switch a.type{ case int: return a.(int) + b.(int) case float32: return a.(float32) + b.(float32) default: panic("not support type") } } 但是這樣每次要增加新的可以接受的結構時,就再需要增加不少的檢查code。而在有了泛型以後,這段的檢查,就可以交由編譯器來處理了。 就可以變成以下這...