Tony Bai

再见样板代码!Go 官方新提案:函数一键转接口 (opens in new tab)

本文永久链接 – 大家好,我是Tony Bai。 在 Go 语言日常开发中,有一个设计几乎人人写过,但写多了又让人觉得极其繁琐、甚至有些“脱裤子放屁”的样板代码。 假设你需要一个只读数据的 io.Reader,但它的行为非常简单(比如只是为了在测试里模拟数据),你通常需要这样写: type ReaderFunc func(p []byte) (n int, err error) func (f ReaderFunc) Read(p []byte) (n int, err error) { return f(p) } 紧接着,在代码中通过 io.Reader(ReaderFunc(myFunc)) 进行双重套娃调用。 这种设计被称为 “适配器型定义”(如标准库中的 http.HandlerFunc)。虽然它工作得很好,但如果每个包都需要针对自己的单方法接口(Single-method Interface)定义一遍这种暖场代码,整个项目就会充斥着大量无意义的样板代码(Boilerplate)。 为了终结这个痛点,Go 语言的积极贡献者 Merovius 提交了一项提案——Issue ...

Read the original article
Sign in to keep reading the full article.

Keyboard Shortcuts

Navigation

Next / previous post
j/k
Open post
oorEnter
Preview post
v

Post Actions

Love post
a
Like post
l
Dislike post
d
Undo reaction
u
Save / unsave
s

Recommendations

Add interest / feed
Enter
Not interested
x

Go to

Home
gh
Interests
gi
Feeds
gf
Likes
gl
History
gy
Changelog
gc
Settings
gs
Discover
gb
Search
/

General

Show this help
?
Submit feedback
!
Close modal / unfocus
Esc

Press ? anytime to show this help