Go 使用默认参数的技巧
golang中没有函数默认参数的设计,因此需要些特别的技巧来实现。
假如我们需要订购一批电脑,其中电脑配置cpu,gpu,内存支持自定义。
type Computer interface {
PowerOn() error
PowerOff() error
}
type computer struct {
name string
cpu string
gpu string
memorySize int
}
定义自定义参数配置,创建一个默认的电脑配置
type pcConfigure struct {
cpu string
gpu string
memorySize int
}
var DefaultPConfigure = pcConfigure {
"i3 2120",
"GTX 660",
12}
创建一个闭包函数,接受自定义的配置参数,返回一个自定义的参数配置
type newPcConfigure func(*pcConfigure)
func newCpuConfigure(cpu string) newPcConfigure {
return func(o *pcConfigure) {
o.cpu = cpu
}
}
func newGpuConfigure(gpu string) newPcConfigure {
return func(o *pcConfigure) {
o.gpu = gpu
}
}
func newMemorySizeConfigure(memorySize int) newPcConfigure {
return func(o *pcConfigure) {
o.memorySize = memorySize
}
}
最后一步,定义一个构造coputer的函数,接受上面的闭包函数为参数
func newComputer(name string, opts ...newPcConfigure) *computer {
pcConfigure := DefaultPConfigure
for _, o := range opts {
o(&pcConfigure)
}
return &computer {
name: name,
cpu: pcConfigure.cpu,
gpu: pcConfigure.gpu,
memorySize: pcConfigure.memorySize}
}
完整代码
package main import (
"fmt"
) type pcConfigure struct {
cpu string
gpu string
memorySize int
} var DefaultPConfigure = pcConfigure {
"i3 2120",
"GTX 660",
12} type newPcConfigure func(*pcConfigure) func newCpuConfigure(cpu string) newPcConfigure {
return func(o *pcConfigure) {
o.cpu = cpu
}
} func newGpuConfigure(gpu string) newPcConfigure {
return func(o *pcConfigure) {
o.gpu = gpu
}
} func newMemorySizeConfigure(memorySize int) newPcConfigure {
return func(o *pcConfigure) {
o.memorySize = memorySize
}
} type Computer interface {
PowerOn() error
PowerOff() error
} type computer struct {
name string
cpu string
gpu string
memorySize int
} func newComputer(name string, opts ...newPcConfigure) *computer {
pcConfigure := DefaultPConfigure
for _, o := range opts {
o(&pcConfigure)
}
return &computer {
name: name,
cpu: pcConfigure.cpu,
gpu: pcConfigure.gpu,
memorySize: pcConfigure.memorySize}
} func (c *computer) PowerOn() (err error) {
return
} func (c *computer) PowerOff() (err error) {
return
} func main () {
pc1 := newComputer("pc1")
fmt.Println(pc1)
pc2 := newComputer("pc2", newCpuConfigure("i7 8700k"), newGpuConfigure("RTX 2080ti"))
fmt.Println(pc2)
}