函数式选项模式

初始化字段时设置默认值,可以使用函数式选项模式,使用方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
type Option struct {
    A string
    B string
    C int
}
 
//第一步
func WithA(a string) func(o *Option) {
    return func(o *Option) {
        o.A = a
    }
}
 
func WithB(b string) func(o *Option)  {
    return func(o *Option) {
        o.B = b
    }
}
 
func WithC(c int) func(o *Option)  {
    return func(o *Option) {
        o.C = c
    }
}
 
//第二步
func newOption2(opts ...OptionFunc) (opt *Option) {
    opt = defaultOption
    for _, o := range opts {
        o(opt)
    }
    return
}
 
//测试
func main() {
    x := newOption("nazha", "小王子", 10)
    fmt.Println(x)
    x = newOption2()
    fmt.Println(x)
    x = newOption2(
        WithA("沙河娜扎"),
        WithC(250),
    )
    fmt.Println(x)
}

  

 

 

参考:Go语言设计模式之函数式选项模式 | 李文周的博客 (liwenzhou.com)

posted @   ☞@_@  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· 单线程的Redis速度为什么快?
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
点击右上角即可分享
微信分享提示