Created
July 24, 2019 07:25
-
-
Save yifanes/ada673e87675c11a0c6e3402b966fe53 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
type options struct { | |
a int64 | |
b string | |
c map[int]string | |
} | |
type ServerOption func(*options) | |
func NewOption(opt ...ServerOption) *options { | |
r := new(options) | |
for _, o := range opt { | |
o(r) | |
} | |
return r | |
} | |
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") | |
s := make(map[int]string) | |
s[0] = "abc" | |
s[1] = "cde" | |
opt3 := WriteC(s) | |
op := NewOption(opt1, opt2, opt3) | |
fmt.Println(op.a, op.b, op.c) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
这段代码主要解决golang中函数参数不可默认,导致不方便使用多种参数组合实例化对象