search
HomeBackend DevelopmentGolangA programming model active in many Go projects

Today we introduce a very popular programming model in the Go language: Functional Options. The problem solved by this pattern is how to configure parameters for objects more dynamically and flexibly. Maybe readers don’t quite understand this pain point, don’t worry, we will explain it in detail below.

Question

# Suppose we define a user structure object User in the code, which has the following properties .

type User struct {
 ID      string    // 必需项
 Name    string    // 必需项
 Age     int       // 非必需项
 Gender  bool      // 非必需项
}

When initializing the object, the simplest way is to directly fill in the attribute value, such as

u := &User{ID: "12glkui234d", Name: "菜刀", Age: 18, Gender: true}

But there is a problem here: User object The attributes in are not necessarily exportable. For example, User has an attribute field called password (the first letter is lowercase, not exported). If a User object needs to be constructed in other modules, the password field cannot be filled.

So we need to define a function to construct the User object. The simplest constructor method that can be thought of is as follows.

func NewUser(id, name string, age int, gender bool) *User {
 return &User{
  ID:     id,
  Name:   name,
  Age:    age,
  Gender: gender,
 }
}

But there are also some problems: for the User object, only the ID and Name properties are required, Age and Gender are non-required, and default values ​​cannot be set. For example, the default value of Age is 0, and the default value of Gender is false, which is obviously unreasonable.

Faced with this problem, what are the solutions we can adopt?

Option 1: Multi-function construction

The crudest solution we can think of is: set up a constructor for each parameter situation . As shown in the following code

func NewUser(id, name string) *User {
 return &User{ID: id, Name: name}
}

func NewUserWithAge(id, name string, age int) *User {
 return &User{ID: id, Name: name, Age: age}
}

func NewUserWithGender(id, name string, gender bool) *User {
 return &User{ID: id, Name: name, Gender: gender}
}

func NewUserWithAgeGender(id, name string, age int, gender bool) *User {
 return &User{ID: id, Name: name, Age: age, Gender: gender}
}

这种方式适合参数较少且不易发生变化的情况。该方式在 Go 标准库中也有使用,例如 net 包中的 Dial 和 DialTimeout 方法。

func Dial(network, address string) (Conn, error) {}
func DialTimeout(network, address string, timeout time.Duration) (Conn, error) {}

但该方式的缺陷也很明显:试想,如果构造对象 User 增加了参数字段 Phone,那么我们需要新增多少个组合函数?

方案二:配置化

另外一种常见的方式是配置化,我们将所有可选的参数放入一个 Config 的配置结构体中。

type User struct {
 ID   string
 Name string
 Cfg  *Config
}

type Config struct {
 Age    int
 Gender bool
}

func NewUser(id, name string, cfg *Config) *User {
 return &User{ID: id, Name: name, Cfg: cfg}
}

这样,我们只需要一个 NewUser()  函数,不管之后增加多少配置选项,NewUser 函数都不会得到破坏。

但是,这种方式,我们需要先构造 Config 对象,这时候对 Config 的构造又回到了方案一中存在的问题。

方案三:函数式选项模式

面对这样的问题,我们还可以选择函数式选项模式。

首先,我们定义一个 Option 函数类型

type Option func(*User)

然后,为每个属性值定义一个返回 Option 函数的函数

func WithAge(age int) Option {
 return func(u *User) {
  u.Age = age
 }
}

func WithGender(gender bool) Option {
 return func(u *User) {
  u.Gender = gender
 }
}

此时,我们将 User 对象的构造函数改为如下所示

func NewUser(id, name string, options ...Option) *User {
 u := &User{ID: id, Name: name}
 for _, option := range options {
  option(u)
 }
 return u
}

按照这种构造方式,我们就可以这样配置 User 对象了

u := NewUser("12glkui234d", "菜刀", WithAge(18), WithGender(true))

以后不管 User 增加任何参数 XXX,我们只需要增加对应的 WithXXX 函数即可,是不是非常地优雅?

Functional Options 这种编程模式,我们经常能在各种项目中找到它的身影。例如,我在 tidb 项目中仅使用 opts ... 关键字搜索,就能看到这么多使用了 Functional Options 的代码(截图还未包括全部)。

A programming model active in many Go projects

Summary

The functional option pattern solves the problem of how to dynamically and flexibly configure parameters for objects, but it needs to be used in appropriate scenarios.

When the configuration parameters of the object are complex, such as many optional parameters, non-imported fields, parameters may increase with the version, etc., then the functional option mode can help very well. us.

The above is the detailed content of A programming model active in many Go projects. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:Go语言进阶学习. If there is any infringement, please contact admin@php.cn delete
go语言有没有缩进go语言有没有缩进Dec 01, 2022 pm 06:54 PM

go语言有缩进。在go语言中,缩进直接使用gofmt工具格式化即可(gofmt使用tab进行缩进);gofmt工具会以标准样式的缩进和垂直对齐方式对源代码进行格式化,甚至必要情况下注释也会重新格式化。

一文浅析Golang中的闭包一文浅析Golang中的闭包Nov 21, 2022 pm 08:36 PM

闭包(closure)是一个函数以及其捆绑的周边环境状态(lexical environment,词法环境)的引用的组合。 换而言之,闭包让开发者可以从内部函数访问外部函数的作用域。 闭包会随着函数的创建而被同时创建。

聊聊Golang中的几种常用基本数据类型聊聊Golang中的几种常用基本数据类型Jun 30, 2022 am 11:34 AM

本篇文章带大家了解一下golang 的几种常用的基本数据类型,如整型,浮点型,字符,字符串,布尔型等,并介绍了一些常用的类型转换操作。

go语言为什么叫gogo语言为什么叫goNov 28, 2022 pm 06:19 PM

go语言叫go的原因:想表达这门语言的运行速度、开发速度、学习速度(develop)都像gopher一样快。gopher是一种生活在加拿大的小动物,go的吉祥物就是这个小动物,它的中文名叫做囊地鼠,它们最大的特点就是挖洞速度特别快,当然可能不止是挖洞啦。

一文详解Go中的并发【20 张动图演示】一文详解Go中的并发【20 张动图演示】Sep 08, 2022 am 10:48 AM

Go语言中各种并发模式看起来是怎样的?下面本篇文章就通过20 张动图为你演示 Go 并发,希望对大家有所帮助!

tidb是go语言么tidb是go语言么Dec 02, 2022 pm 06:24 PM

是,TiDB采用go语言编写。TiDB是一个分布式NewSQL数据库;它支持水平弹性扩展、ACID事务、标准SQL、MySQL语法和MySQL协议,具有数据强一致的高可用特性。TiDB架构中的PD储存了集群的元信息,如key在哪个TiKV节点;PD还负责集群的负载均衡以及数据分片等。PD通过内嵌etcd来支持数据分布和容错;PD采用go语言编写。

【整理分享】一些GO面试题(附答案解析)【整理分享】一些GO面试题(附答案解析)Oct 25, 2022 am 10:45 AM

本篇文章给大家整理分享一些GO面试题集锦快答,希望对大家有所帮助!

聊聊Golang自带的HttpClient超时机制聊聊Golang自带的HttpClient超时机制Nov 18, 2022 pm 08:25 PM

​在写 Go 的过程中经常对比这两种语言的特性,踩了不少坑,也发现了不少有意思的地方,下面本篇就来聊聊 Go 自带的 HttpClient 的超时机制,希望对大家有所帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools