发现一个高逼格的golang“构造函数”写法

栏目: Go · 发布时间: 7年前

内容简介:如上,最近看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语言基础

C语言基础

安博教育集团 / 2012-2 / 37.00元

《C语言基础》深入浅出地介绍了C语言程序设计的基础知识,内容涉及C语言基础、算法基础、变量、数据类型、运算符、输入/输出相关函数、选择结构、循环结构、各种表达式、数组、字符串、指针、函数、结构体、ISO C99的扩展语法等。全书内容丰富,结构严谨,层次清晰,语言生动,论述精准而深刻,实例丰富而实用。 《C语言基础》不仅适合用做计算机职业培训的首选教材,也可作为普通高校教材使用,更是C语言初学......一起来看看 《C语言基础》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

html转js在线工具
html转js在线工具

html转js在线工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试