Table of Contents
Correct answer
Home Backend Development Golang Create a GO structure only if certain conditions are met

Create a GO structure only if certain conditions are met

Feb 08, 2024 pm 09:05 PM
Memory usage

仅当满足特定条件时才创建 GO 结构

php editor Zimo will introduce you to an important feature, which is the creation of GO structures under specific conditions. This feature allows us to determine whether to create a GO structure as needed, thereby improving the efficiency and performance of the program. By using this feature rationally, we can avoid unnecessary creation of GO structures, reduce memory usage and garbage collection pressure, and improve the running efficiency of the program. In this article, we will detail how to use this feature and give some examples of practical applications.

Question content

My go code snippet is as follows:

type mystruct struct {
   a int
}

if a == nil {
        cond = 0
        var a_mystruct_obj mystruct  // if this condition is satified then only create this a_mystruct_obj obj
    } else if b == nil {
        cond = 1
        var b_mystruct_obj mystruct  // if this condition is satified then only create this b_mystruct_obj obj

    } else {
        cond = 2 // // if this condition is satified then create both the above structure objects  a_mystruct_obj & b_mystruct_obj.
         // is having the below declaration again in else a valid go code ?
        var a_mystruct_obj mystruct
        var b_mystruct_obj mystruct
    }
Copy after login

I have c background. This would be simple in c. Is there dynamic memory allocation in go? How can I achieve this in go?

Is it valid go code to declare 2 again in else?

var A_mystruct_obj MyStruct
    var B_mystruct_obj MyStruct
Copy after login

Or do I need to have some kind of runtime polymorphism here.

renew:

I tried doing this but it didn't even compile as expected.

https://go.dev/play/p/ioq81aexgjn

Update again

I tried this and it seems to work. Is this okay?

https://go.dev/play/p/r_ywzmkgrps


Correct answer


There are two problems in your code:

  1. Your variables are declared in an enclosing scope, so they are not accessible from outside that scope (if/else clauses)
  2. Your variable is declared as a value

When you solve the first problem, that is by moving the variable declarations outside the scope of the if clause so that they can be accessed by the code following the if statement:

    var a_mystruct_obj mystruct
    var b_mystruct_obj mystruct
    if a == nil {
        cond = 0
        // initialise a_mystruct
    } else if b == nil {
        cond = 1
        // initialise b_mystruct
    } else {
        cond = 2
        // initialise a_mystruct and b_mystruct
    }
Copy after login

Now both variables are declared, and both variables are initialized with the newly allocated mystruct regardless of which clause in the if statement is reached.

To solve this problem, change the variable to a pointer and assign the desired value in the corresponding branch of the if statement:

    var a_mystruct_obj *mystruct
    var b_mystruct_obj *mystruct
    if a == nil {
        cond = 0
        a_mystruct_obj = &mystruct{}
    } else if b == nil {
        cond = 1
        b_mystruct_obj = &mystruct{}
    } else {
        cond = 2
        a_mystruct_obj = &mystruct{}
        b_mystruct_obj = &mystruct{}
    }
Copy after login

Bonus Tip: Future you will thank you Refactor this into a pair of statements, determine if you need a or b or Both, then simplify your compound if statement as two separate statements, initializing a or b respectively:

    var A_mystruct_obj *MyStruct
    var B_mystruct_obj *MyStruct

    areq := a == nil || (..condition 2..) 
    breq := b == nil || (..condition 2..) 
    if areq {
        A_mystruct_obj = &MyStruct{}
    }
    if breq {
        B_mystruct_obj = &MyStruct{}
    }
Copy after login

The purpose is to avoid logical duplication (dry principle: Don’t repeat yourself) and separation of concerns. That is, separate the question of whether a and/or b is needed from the question of when initialization of a and b is needed. em> Required.

Note: It's not possible to be more specific about how to express condition 2, since it's not clear from the code you posted what the condition is.

The above is the detailed content of Create a GO structure only if certain conditions are met. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1254
24
What to do if your Huawei phone has insufficient memory (Practical methods to solve the problem of insufficient memory) What to do if your Huawei phone has insufficient memory (Practical methods to solve the problem of insufficient memory) Apr 29, 2024 pm 06:34 PM

Insufficient memory on Huawei mobile phones has become a common problem faced by many users, with the increase in mobile applications and media files. To help users make full use of the storage space of their mobile phones, this article will introduce some practical methods to solve the problem of insufficient memory on Huawei mobile phones. 1. Clean cache: history records and invalid data to free up memory space and clear temporary files generated by applications. Find "Storage" in the settings of your Huawei phone, click "Clear Cache" and select the "Clear Cache" button to delete the application's cache files. 2. Uninstall infrequently used applications: To free up memory space, delete some infrequently used applications. Drag it to the top of the phone screen, long press the "Uninstall" icon of the application you want to delete, and then click the confirmation button to complete the uninstallation. 3.Mobile application to

Detailed steps for cleaning memory in Xiaohongshu Detailed steps for cleaning memory in Xiaohongshu Apr 26, 2024 am 10:43 AM

1. Open Xiaohongshu, click Me in the lower right corner 2. Click the settings icon, click General 3. Click Clear Cache

The impact of the AI ​​wave is obvious. TrendForce has revised up its forecast for DRAM memory and NAND flash memory contract price increases this quarter. The impact of the AI ​​wave is obvious. TrendForce has revised up its forecast for DRAM memory and NAND flash memory contract price increases this quarter. May 07, 2024 pm 09:58 PM

According to a TrendForce survey report, the AI ​​wave has a significant impact on the DRAM memory and NAND flash memory markets. In this site’s news on May 7, TrendForce said in its latest research report today that the agency has increased the contract price increases for two types of storage products this quarter. Specifically, TrendForce originally estimated that the DRAM memory contract price in the second quarter of 2024 will increase by 3~8%, and now estimates it at 13~18%; in terms of NAND flash memory, the original estimate will increase by 13~18%, and the new estimate is 15%. ~20%, only eMMC/UFS has a lower increase of 10%. ▲Image source TrendForce TrendForce stated that the agency originally expected to continue to

What to do if the Edge browser takes up too much memory What to do if the Edge browser takes up too much memory What to do if the Edge browser takes up too much memory What to do if the Edge browser takes up too much memory May 09, 2024 am 11:10 AM

1. First, enter the Edge browser and click the three dots in the upper right corner. 2. Then, select [Extensions] in the taskbar. 3. Next, close or uninstall the plug-ins you do not need.

How to fine-tune deepseek locally How to fine-tune deepseek locally Feb 19, 2025 pm 05:21 PM

Local fine-tuning of DeepSeek class models faces the challenge of insufficient computing resources and expertise. To address these challenges, the following strategies can be adopted: Model quantization: convert model parameters into low-precision integers, reducing memory footprint. Use smaller models: Select a pretrained model with smaller parameters for easier local fine-tuning. Data selection and preprocessing: Select high-quality data and perform appropriate preprocessing to avoid poor data quality affecting model effectiveness. Batch training: For large data sets, load data in batches for training to avoid memory overflow. Acceleration with GPU: Use independent graphics cards to accelerate the training process and shorten the training time.

For only $250, Hugging Face's technical director teaches you how to fine-tune Llama 3 step by step For only $250, Hugging Face's technical director teaches you how to fine-tune Llama 3 step by step May 06, 2024 pm 03:52 PM

The familiar open source large language models such as Llama3 launched by Meta, Mistral and Mixtral models launched by MistralAI, and Jamba launched by AI21 Lab have become competitors of OpenAI. In most cases, users need to fine-tune these open source models based on their own data to fully unleash the model's potential. It is not difficult to fine-tune a large language model (such as Mistral) compared to a small one using Q-Learning on a single GPU, but efficient fine-tuning of a large model like Llama370b or Mixtral has remained a challenge until now. Therefore, Philipp Sch, technical director of HuggingFace

Which one has better web performance, golang or java? Which one has better web performance, golang or java? Apr 21, 2024 am 12:49 AM

Golang is better than Java in terms of web performance for the following reasons: a compiled language, directly compiled into machine code, has higher execution efficiency. Efficient garbage collection mechanism reduces the risk of memory leaks. Fast startup time without loading the runtime interpreter. Request processing performance is similar, and concurrent and asynchronous programming are supported. Lower memory usage, directly compiled into machine code without the need for additional interpreters and virtual machines.

Let large models no longer be 'big Mac'. This is the latest review of efficient fine-tuning of large model parameters. Let large models no longer be 'big Mac'. This is the latest review of efficient fine-tuning of large model parameters. Apr 28, 2024 pm 04:04 PM

The AIxiv column is a column where this site publishes academic and technical content. In the past few years, the AIxiv column of this site has received more than 2,000 reports, covering top laboratories from major universities and companies around the world, effectively promoting academic exchanges and dissemination. If you have excellent work that you want to share, please feel free to contribute or contact us for reporting. Submission email: liyazhou@jiqizhixin.com; zhaoyunfeng@jiqizhixin.com. Recently, large-scale AI models such as large language models and Vincentian graph models have developed rapidly. Under this situation, how to adapt to rapidly changing needs and quickly adapt large models to various downstream tasks has become an important challenge. Limited by computing resources, traditional full-parameter micro

See all articles