SoFunction
Updated on 2025-03-05

A detailed explanation of the Option design pattern in Go language

I will not explain too much about what a design pattern is here. Just Baidu Google on your own. Let's talk about the Option design pattern. This word is translated intoOptionsMeaning.

It is usually used when initializing data.

type User struct {
    // Values ​​that must be initialized    Username string
    Age int
    
    // Values ​​that are initialized for non-essential    Password string
}

In a structure, some fields must be initialized, while others do not. Fields that do not need to be initialized are called optional. Users initialize it according to their actual needs.

Generally speaking, for this structure, whether it is a field that must be initialized or not, it is a private field and will not be exposed to the outside world.

Below is a standard Option design pattern

// Define an Option function signaturetype UserOption func(user *User)

// Provide an optional functionfunc WithUserPassword(password string) UserOption {
    return func(user *User) {
         = password
    }
}

type User struct {
    // Values ​​that must be initialized    Username string
    Age int
    
    // Values ​​that are initialized for non-essential    Password string
}

// Define a method to initialize Userfunc NewUser(username string, age int, opts...UserOption) *User {
    user := &User{
        Username: username,
        Age: age,
    }
    for _, opt := range opts {
        opt(user)
    }
    return user
}

step

  • Define a structure, all internal fields are private, and there are fields that must be initialized and fields that are not necessary.
  • Define an Option function signature, the parameter is a structure pointer, and must be a structure pointer, because only the pointer can set the value
  • Define a method to initialize a structure. The parameters are the field values ​​that the structure must initialize, plus an Option function slice. The return value can be a structure or a pointer structure.
  • The initialization structure method first initializes the most basic structure, and then traverses the Option function to slice it.
  • The defined Option function implementation is best started with With, standardized, and not followed.

Option mode variant

// Define an Option function signaturetype UserOptionErr func(user *User) error

// Provide an optional functionfunc WithUserPassword(password string) UserOption {
    return func(user *User) error {
        if password == "" {
            return ("password cannot be empty")
        }
         = password
        return nil
    }
}

type User struct {
    // Values ​​that must be initialized    Username string
    Age int
    
    // Values ​​that are initialized for non-essential    Password string
}

// Define a method to initialize Userfunc NewUser(username string, age int, opts...UserOption) (*User, error) {
    user := &User{
        Username: username,
        Age: age,
    }
    for _, opt := range opts {
        if err := opt(user); err != nil {
            return nil, err
        }
    }
    return user, nil
}

You should have discovered that it is to modify the return value of the Option function signature. This mode can be used to verify the parameters of the Option function. Since there has been a change here, the method of initializing the structure also needs to be changed accordingly.

The Option mode can be used in many scenarios and is also very useful. Remember that it is used when initializing data, and the code pattern is relatively fixed.

This is the article about this article about a detailed explanation of the Option design pattern in Go language. For more related content on Go Option design pattern, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!