From 246983ea3a957754b5e8472df5df0a266707bb5f Mon Sep 17 00:00:00 2001 From: asahi Date: Wed, 8 Jan 2025 03:33:27 +0800 Subject: [PATCH] =?UTF-8?q?=E9=98=85=E8=AF=BBgolang=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Golang/Golang Document.md | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/Golang/Golang Document.md b/Golang/Golang Document.md index e783162..c323f38 100644 --- a/Golang/Golang Document.md +++ b/Golang/Golang Document.md @@ -100,3 +100,40 @@ func main() { ``` 上述示例中,分别向`/albums`路径注册了GET和POST的处理handler,并在`localhost:8080`上对服务进行监听。 +## golang generic +### 不使用泛型的代码编写 +如果不使用泛型,那么对于不同数值类型的求和,需要编写多个版本的代码,示例如下: +```go +// SumInts adds together the values of m. +func SumInts(m map[string]int64) int64 { + var s int64 + for _, v := range m { + s += v + } + return s +} + +// SumFloats adds together the values of m. +func SumFloats(m map[string]float64) float64 { + var s float64 + for _, v := range m { + s += v + } + return s +} + +``` +上述针对int64和float64的版本,编写了两个独立的函数 + +### 使用泛型的代码编写 +对于泛型方法的编写,其相对普通方法多了`类型参数`,在对泛型方法进行调用时,可以传递类型参数和普通参数。 + +对于每个`parameter type`,其都有对应的`type constraint`。每个`type constraint`都制定了在调用泛型方法时,可以对`parameter type`指定哪些类型。 + +`type parameter`通常都带代表一系列类型的集合,但是在编译时type parameter则是代表由调用方传递的`type argument`类型。如果type argument类型不满足type constraint的要求,那么该代码则不会被成功编译。 + + + + + +