Go 使用默认参数的技巧

Functional Options Pattern in 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)
}

golang实现参数可变的技巧的更多相关文章

  1. Java可变参数/可变长参数

    Java可变参数/可变长参数 传递的参数不确定长度,是变长的参数,例如小例子: package demo; public class Demo { public static int sum(int ...

  2. Golang fmt包使用小技巧

    h1 { margin-top: 0.6cm; margin-bottom: 0.58cm; direction: ltr; color: #000000; line-height: 200%; te ...

  3. 随想:目标识别中,自适应样本均衡设计,自适应模型结构(参数可变自适应,模型结构自适应,数据类别or分布自适应)

    在现在的机器学习中,很多人都在研究自适应的参数,不需要人工调参,但是仅仅是自动调参就不能根本上解决 ai识别准确度达不到实际生产的要求和落地困难的问题吗?结论可想而知.如果不改变参数,那就得从算法的结 ...

  4. java参数可变方法

    java中允许一个方法中存在多个参数 public class Parmvarexmple { //参数可变的方法 public int sum(int...n) { int tempSum=0; f ...

  5. Golang的防坑小技巧

    Golang的防坑小技巧 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 作为一名小白,在之前没有接触到编程的小伙伴,难免会踩到一些坑,比如说刚刚入门的时候你需要安装环境,学习Gol ...

  6. Python星号*与**用法分析 What does ** (double star/asterisk) and * (star/asterisk) do for parameters? 必选参数 默认参数 可变参数 关键字参数

    python中*号**的区别 - CSDN博客 https://blog.csdn.net/qq_26815677/article/details/78091452 定义可变参数和定义 list 或 ...

  7. golang的超时处理使用技巧

    原文链接:https://www.zhoubotong.site/post/57.html golang的超时处理 2天前Go实例技巧25   大家知道Select 是 Go 中的一个控制结构,每个  ...

  8. SQL Server存储过程Return、output参数及使用技巧

    SQL Server目前正日益成为WindowNT操作系统上面最为重要的一种数据库管理系统,随着 SQL Server2000的推出,微软的这种数据库服务系统真正地实现了在WindowsNT/2000 ...

  9. python函数的参数-可变参数,关键字参数

    # -*- coding: utf-8 -*- #coding=utf-8 ''' @author: tomcat @license: (C) Copyright 2017-2019, Persona ...

随机推荐

  1. 2019西湖论剑web wp

    发在正文前 这应该是自己在安全圈摸爬滚打两年多以来第一次正规的ctf比赛.没解出flag,没截图,只提供了一些思路. 遥想往昔,初入大学,带着对PT的向往,一个人穿行在幽暗的图书馆,翻阅啃读一本本安全 ...

  2. canvas简易画板。

    在学canvas的时候,想到可以做一个自己用来画画的简易画板,加上canvas的基础都已经学完,便尝试做了一个画板.如图 1.获取标签. var c=document.getElementById(' ...

  3. Scrum冲刺阶段6

    成员今日完成的任务 人员 任务 何承华 学习后端设计 陈宇 后端设计 丁培辉 学习后端设计 温志铭 信息界面设计 杨宇潇 信息界面界面设计 张主强 服务器构建学习 成员遇到的问题 人员 问题 何承华 ...

  4. 聚类K-Means

    import numpy as np x=np.random.randint(0,52,52) x k=3 y=np.zeros(20) y array([ 0., 0., 0., 0., 0., 0 ...

  5. 每日一练ACM 2019.0416

    2019.04.16     Problem Description Your task is to Calculate the sum of some integers.   Input Input ...

  6. hql- 使用like的小坑①

    like '%_test_' 要把反斜杠进行转义like '%\_test\_'

  7. UITextField 输入金额,小数点的控制输入

    #pragma mark --- UITextFieldDelegate ---- (BOOL)textField:(UITextField *)textField shouldChangeChara ...

  8. npm遇到的问题--npm install 执行报错 /bin/git submodule update -q --init --recursive

    1.执行npm i 安装依赖时,报错:cannot read property 'match' of undefined 据说是npm本地缓存导致 解决方案: rm -rf package-lock. ...

  9. c语言构建哈希表

    /*哈希查找 *哈希函数的构造方法常用的有5种.分别是: *数字分析法 *平方取中法 *分段叠加 *伪随机数 *除留取余法 *这里面除留取余法比较常用 *避免哈希冲突常用的方法有4种: *开放定址法( ...

  10. HTML基本格式和文本元素(标签)介绍

    <!doctype html>//声明文档类型 <html lang="zh-cn">//文档开始,后面是声明是中文页面的意思,en是英语的意思 <h ...