内容简介:如上,最近看grpc的源码,发现了里面一种高逼格的构造函数的写法,表示震惊,学到了新姿势。
package main
import (
"fmt"
)
type options struct {
a int64
b string
c map[int]string
}
func NewOption(opt ...ServerOption) *options {
r := new(options)
for _, o := range opt {
o(r)
}
return r
}
type ServerOption func(*options)
func WriteA(s int64) ServerOption {
return func(o *options) {
o.a = s
}
}
func WriteB(s string) ServerOption {
return func(o *options) {
o.b = s
}
}
func WriteC(s map[int]string) ServerOption {
return func(o *options) {
o.c = s
}
}
func main() {
opt1 := WriteA(int64(1))
opt2 := WriteB("test")
opt3 := WriteC(make(map[int]string,0))
op := NewOption(opt1, opt2, opt3)
fmt.Println(op.a, op.b, op.c)
}
如上,最近看grpc的源码,发现了里面一种高逼格的构造函数的写法,表示震惊,学到了新姿势。
package main
import (
"fmt"
)
type options struct {
a int64
b string
c map[int]string
}
func (o *options) writeA(a int64) *options {
o.a = a
return o
}
func (o *options) writeB(b string) *options {
o.b = b
return o
}
func (o *options) writeC(c map[int]string) *options {
o.c = c
return o
}
func main() {
op := new(options)
op.writeA(int64(1)).writeB("test").writeC(make(map[int]string, 0))
fmt.Println(op.a, op.b, op.c)
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
C++ Primer 中文版(第 5 版)
[美] Stanley B. Lippman、[美] Josée Lajoie、[美] Barbara E. Moo / 王刚、杨巨峰 / 电子工业出版社 / 2013-9-1 / CNY 128.00
这本久负盛名的 C++经典教程,时隔八年之久,终迎来史无前例的重大升级。除令全球无数程序员从中受益,甚至为之迷醉的——C++ 大师 Stanley B. Lippman 的丰富实践经验,C++标准委员会原负责人 Josée Lajoie 对C++标准的深入理解,以及C++ 先驱 Barbara E. Moo 在 C++教学方面的真知灼见外,更是基于全新的 C++11标准进行了全面而彻底的内容更新。......一起来看看 《C++ Primer 中文版(第 5 版)》 这本书的介绍吧!