惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
Blog — PlanetScale
Blog — PlanetScale
腾讯CDC
aimingoo的专栏
aimingoo的专栏
Microsoft Azure Blog
Microsoft Azure Blog
A
About on SuperTechFans
J
Java Code Geeks
G
Google Developers Blog
N
Netflix TechBlog - Medium
Vercel News
Vercel News
Y
Y Combinator Blog
Recent Announcements
Recent Announcements
I
InfoQ
Stack Overflow Blog
Stack Overflow Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
T
The Blog of Author Tim Ferriss
罗磊的独立博客
GbyAI
GbyAI
小众软件
小众软件
大猫的无限游戏
大猫的无限游戏
WordPress大学
WordPress大学
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

Jiajun的技术笔记

你好,2026! TiDB 源码阅读(六):TiDB Coprocessor 源码解析 性能优化的核心思想 TiDB 源码阅读(五):索引 TiDB 源码阅读(四):AST、逻辑计划、物理计划 CockroachDB Serverless Architecture podman 无故退出 Cursor Control-L (CTRL-L) Keyboard Shortcuts in Terminal Replace docker with podman Using xmonad with xfce4 A RC script for freebsd frpc 自己动手写一个k8s controller AI 会取代你的(编程)岗位吗? 自建DERP服务器提升Tailscale连接速度(使用Nginx转发) 自动升级Docker容器 再读《程序员修炼之道-从小工到专家》 让浏览器下载文件 再读《软件随想录》/《黑客与画家》/《软技能》 HTTP 压力测试中的 Coordinated Omission 2的补码 编程语言中的 context 是什么? flutter macOS 构建出错 Flatpak 使用小记 Golang CAS 操作是怎么实现的 PostgreSQL 当MQ来使用 Clash 结合 工作VPN 的网络设计 使用 PostgreSQL 搭建 JuiceFS PostgreSQL 配置优化和日志分析 有GitHub Copilot?那就可以搭建你的ChatGPT4服务 窗口函数的使用(以PG为例)
Golang的可选参数实践
Jiajun Huang · 2020-04-20 · via Jiajun的技术笔记

Golang处理可选参数+默认参数的时候,常见的代码是这样的:

type Queue struct {
	Name string
}

func NewQueue(name string) *Queue {
	return &Queue{name}
}

然而随着项目的发展,这个参数可能会变多:

type Queue struct {
	Name     string
	MaxLimit int
}

那么这个时候要如何处理呢?有几种方案:

  • 破坏兼容性:使用 func NewQueue(name string, maxLimit int) *Queue 的方式
  • 不破坏兼容性,增加 func NewQueueWithLimit(name string, maxLimit int) *Queue,从而保留原来的方式
  • 破坏兼容性,使用一个 Config 来保存配置,就变成了 func NewQueue(config *QueueConfig) *Queue,但是这种方式有一个 很大的缺点,就是不好处理零值,零值到底是零值,还是填的刚好是零值?我该不该用默认参数替代之?

因此就演变出下面这种方式,在我看来是一个很好的解决方案:

type Queue struct {
	Name     string
	MaxLimit int

	// monitor
	MonitorInterval int
}

type QueueOption func(*Queue)

func WithMaxLimit(max int) QueueOption {
	return func(q *Queue) {
		q.MaxLimit = max
	}
}

func WithMonitorInterval(seconds int) QueueOption {
	return func(q *Queue) {
		q.MonitorInterval = seconds
	}
}

func NewQueue(name string, options ...QueueOption) *Queue {
	queue := &Queue{name, 10, 5}

	for _, o := range options {
		o(queue)
	}

	return queue
}

使用起来,就可以这样:NewQueue("abcd", WithMaxLimit(10)),然而后面的 With 函数是可选的,如果不选,就会使用我们的默认值, 这样做的好处是不会破坏兼容性,以后如果增加了更多选项,那么增加一个 With函数即可。

不过天下没有免费的午餐,这种方式的弊端也很明显,就是比较费键盘 — 每次新增一个选项时都要新增加一个函数。


参考资料: