SoFunction
Updated on 2025-03-05

Tips for using anonymous structures in Go

Today I will share with you a small tip for using anonymous structures to improve Go programming efficiency. It has no technical depth and is a small experience accumulated in daily code writing process to improve your programming efficiency.

The reason why this technique improves efficiency is mainly reflected in two aspects:

  • Reduce some type definitions that will not be reused
  • Save time to worry about what name to give a type

Especially the second item, the name can be reflected through the anonymous structure. It has no type name itself, which can save a lot of time when thinking about the name. Another one can reduce the misunderstandings caused by the wrong name to others. After all, not everyone will name them according to the English lexical method when programming.

Let me start with ordinary structures and show you how to use anonymous structures to improve coding efficiency.

Named structure

Named structures are ordinary structures that are usually used.

Everyone knows that structures are used to organize a set of fields together to abstractly express things in the real world in Go language, similar to "blueprint".

For example, defining a structure named Car means "car" in the program

// Define the structure type 'car'type car struct {
    make    string
    model   string
    mileage int
}

You can just refer to this structure by its name where you use it, such as creating an instance of the structure defined above.

// Create an instance of carnewCar := car{
    make:    "Ford",
    model:   "taurus",
    mileage: 200000,
}

Anonymous structure

Anonymous structures, as the name implies, are structures without names, and are usually only used for structure types that are only used once in the code, such as

func showMyCar() {
    newCar := struct {
        make    string
        model   string
        mileage int
    }{
        make:    "Ford",
        model:   "Taurus",
        mileage: 200000,
    }
    ()
}

The anonymous structure declared in the above function is assigned to the variables in the function, so it can only be used in the function.

If a structure is only used once after initialization, it will be very convenient to use anonymous structures. There is no need to define too many structure types in the program's package. For example, after parsing the response of the interface to the structure, you can use anonymous structures

Used to parse interface responses

func createCarHandler(w , req *) {
    defer ()
    decoder := ()
    newCar := struct {
        Make    string `json:"make"`
        Model   string `json:"model"`
        Mileage int    `json:"mileage"`
    }{}
    err := (&newCar)
    if err != nil {
        (err)
        return
    }
    ......
    return
}

Codes like the above are generally written in the control layer. After parsing the request through an anonymous structure instance, the corresponding DTO or domain object can be created for use by the service layer or domain layer.

Some people may ask why not directly parse the API response into the DTO object. Here we will say that the use scenario of anonymous structures is only used when it feels that it is not worth or convenient to set a Struct. For example, after the program receives the interface response, it needs to process it according to business rules before creating a DTO instance, it is very suitable to use an anonymous structure to parse the response first.

More robust than using map

Here we will talk about the benefits of using anonymous structures.

Using anonymous resolution interface response is more important than parsing the response tomap[string]interface{}Type variables are much better. When json data is parsed into an anonymous structure, type checking will be performed during the parsing process, which will be safer. When using it, it is directly passedAccess fields are also bettermapMore convenient and intuitive to access.

Public fields used to define project conventions

In addition to the above situation where the structure is only used once after initialization, it is also very convenient for some public fields to declare anonymous structures when defining the return or DTO of each interface in the project.

Generally, when starting a project, we will agree on the response value structure of the interface provided by the project, for example, the response must includeCodeMsgDataThere are three fields, each interface will further define the returned Data structure. At this time, using anonymous structure questions can save some encoding efficiency.

For example, the followingReponseDefinition of structure type

type UserCouponResponse struct {
 Code int64  `json:"code"`
 Msg  string `json:"message"`
 Data []*struct {
  CouponId           int    `json:"couponId"`
  ProdCode           string `json:"prodCode"`
  UserId             int64  `json:"userId"`
  CouponStatus       int    `json:"couponStatus"`
  DiscountPercentage int    `json:"discount"`
 } `json:"data"`
}

Just save it first to define a UserCoupon type

type UserCoupon struct {
    CouponId           int    `json:"couponId"`
    ProdCode           string `json:"prodCode"`
    UserId             int64  `json:"userId"`
    CouponStatus       int    `json:"couponStatus"`
    DiscountPercentage int    `json:"discount"`
} 

Use the defined UserCoupon in the Response statement again

type UserCouponResponse struct {
    Code int64  `json:"code"`
    Msg  string `json:"message"`
    Data []*UserCoupon `json:"data"`
}

Of course, if UserCoupon is a type that will be used elsewhere in your project, then declare it first and then use it in the Response structure. As long as the type that will be used multiple times, it is recommended to declare it as a normal structure type.

Or the same sentence is used when you think "Is there a type to define?", and using it well can indeed improve the productivity of the point code.

This is the end of this article about the skills of using anonymous structures in Go. For more related content on Go anonymous structures, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!