Skip to content

Instantly share code, notes, and snippets.

@yifanes
Created July 24, 2019 07:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yifanes/ada673e87675c11a0c6e3402b966fe53 to your computer and use it in GitHub Desktop.
Save yifanes/ada673e87675c11a0c6e3402b966fe53 to your computer and use it in GitHub Desktop.
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)
}
@yifanes
Copy link
Author

yifanes commented Jul 24, 2019

这段代码主要解决golang中函数参数不可默认,导致不方便使用多种参数组合实例化对象

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment