Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the Golang functional option mode

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to realize the Golang functional option mode". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to implement the Golang functional option mode.

Overview

Recently, I saw a good piece of code when I read the source code, but I didn't quite understand why it was written this way at the time.

Let's take a look at the source code:

Type User struct {ID string Name string Age int Email string Phone string Gender string} type Option func (* User) func WithAge (age int) Option {return func (u * User) {u.Age = age}} func WithEmail (email string) Option {return func (u * User) {u.Email = Email}} func WithPhone (phone string) Option {return func (u * User) {u.Phone = phone}} func WithGender (gender string) Option {return func (u * User) {u.Gender = gender}} func NewUser (id string Name string, options... func (* User) (* User, error) {user: = User {ID: id, Name: name, Age: 0, Email: ", Phone:", Gender: "female",} for _ Option: = range options {option (& user)} / /. Return & user, nil} func main () {user, err: = NewUser ("1", "Ada", WithAge (18), WithPhone ("123456")) if err! = nil {fmt.Printf ("NewUser: err:%v", err)} fmt.Printf ("NewUser Success")}

At that time, I didn't quite understand why the constructor NewUser was written in this way. Later, after looking at the data, I realized that it was a design pattern-functional option (functional options) pattern.

What is the functional option mode, why is it written this way, and what does this programming pattern solve?

In fact, it is to solve the problem of dynamic and flexible configuration of different parameters.

Suppose we have a need:

There are many options for registering an account on the website, which can be filled in or not. Your User object will be initialized based on the information you fill in.

Overloaded function

If you have the programming foundation of C++ or Java, your first reaction should be function overloading.

But because the Golang language doesn't support overloaded functions like C++, you have to use different function names to deal with different configuration options.

Like this:

Func NewUserDefault (id string, name string) (* User, error) {return & User {ID: id, Name: name}, nil} func NewUserWithPhone (id string, name string, phone string) (* User, error) {return & User {ID: id, Name: name, Phone: phone}, nil} func NewUserWithEmail (id string, name string, email string) (* User, error) {return & User {ID: ID, id: id, Name: Name}, Name}

If there are only two or three parameters, it is relatively simple, but the combination of more options looks messy.

Configuration

At this point, we may think of configuration.

Put all the optional parameters into a struct of Config.

Type Config struct {Age int Email string Phone string Gender string}

Then put Config into User's struct.

Type User struct {ID string Name string Conf * Config}

So, all we need is a function of NewUser (), and we need to construct a Config object before using it.

Func NewUser (id string, name string, conf * Config) (* User, error) {/ /...} / / Using the default configuratrionuser, _: = NewUser ("1", "Ada", nil) conf: = Config {Age:18, Phone: "123456"} user2, _: = NewUser ("2", "Bob", & conf)

This code looks good, and a lot of the open source libraries I use are written in the same way. The problem of combining multiple parameters is solved by introducing a Config object.

Builder mode

Some students who often use Java will think of Builder mode.

So you can use it in the following way:

User: = new (UserBuilder) .Create ("1", "Ada"). Age (18). Phone (123456). Gender ("female"). Build ()

You need to introduce an abstract UserBuilder object to wrap the User object, and eventually Build a User object to return.

Functional option mode

The functional option mode first needs to define a function type:

Type Option func (* User)

Then, we define a set of functions that return functions:

Func WithAge (age int) Option {return func (u * User) {u.Age = age}} func WithEmail (email string) Option {return func (u * User) {u.Email = email}} func WithPhone (phone string) Option {return func (u * User) {u.Phone = phone}} Func WithGender (gender string) Option {return func (u * User) {u.Gender = gender}}

The difference between this pattern and Builder mode is that Builder mode returns a * User object, while Functional Options returns a function type func (* User).

The above set of code passes in a parameter and returns a function that sets its own User parameter.

In this way, it is convenient for us to initialize uniformly in NewUser. The loop invokes our function type. Option & user)

Func NewUser (id string, name string, options... func (* User)) (* User, error) {user: = User {ID: id, Name: name, Age: 0, Email: ", Phone:", Gender: "female" } for _, option: = range options {option (& user)} / /. Return & user, nil}

The calling method is as follows:

User1, err: = NewUser ("1", "Ada") user2, err: = NewUser ("2", "Bob", WithPhone ("123456"), WithGender ("male"))

This looks neat and elegant, and the external interface has only one NewUser.

Compared to the Builder schema, there is no need to introduce a Builder object.

Compared with the configured mode, there is no need to introduce a new Config.

At this point, I believe you have a deeper understanding of "how to implement the Golang functional option mode". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report