阅读golang文档
This commit is contained in:
@@ -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的要求,那么该代码则不会被成功编译。
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user