Search code examples
if-statementgostructpreprocessor

How to add an if statement to a struct initialization


I'm trying to add an if statement in a nested struct, and whenever I try to build I get: syntax error: unexpected if, expecting expression.

I've found a simple code that shows what i'm trying to do:

package main

import "fmt"

type Salary struct {
    Basic, HRA, TA float64
}

type Employee struct {
    FirstName, LastName, Email string
    Age                        int
    MonthlySalary              []Salary
}

func main() {
    e := Employee{
        FirstName: "Mark",
        LastName:  "Jones",
        Email:     "mark@gmail.com",
        Age:       25,
        MonthlySalary: []Salary{
            Salary{
                Basic: 15000.00,
                HRA:   5000.00,
                TA:    2000.00,
            },
            Salary{          //i want to add a condition "if true" then add this salary struct
                Basic: 16000.00,
                HRA:   5000.00,
                TA:    2100.00,
            },                // till here
            Salary{
                Basic: 17000.00,
                HRA:   5000.00,
                TA:    2200.00,
            },
        },
    }

And I found that this might be done through preprocessor, which I'm totally clueless about.

Please note that the struct is imported from another package on my original code and I can't change the way it's declared and used.


Solution

  • You cannot put logic inline in a struct. You must do it outside of the variable declaration. But this is easy. For example:

    func main() {
        // Initialize a slice of `salaries` with the first
        // value you know you need.
        salaries := []Salary{
            {
                Basic: 15000.00,
                HRA:   5000.00,
                TA:    2000.00,
            },
        }
        if /* your condition */ {
            // conditionally add the second one
            salaries = append(salaries, Salary{
                Basic: 16000.00,
                HRA:   5000.00,
                TA:    2100.00,
            })
        }
        // And finally add the last one
        salaries = append(salaries, Salary{
            Basic: 17000.00,
            HRA:   5000.00,
            TA:    2200.00,
        })
        e := Employee{
            FirstName: "Mark",
            LastName:  "Jones",
            Email:     "mark@gmail.com",
            Age:       25,
            // And here include them in the variable declaration
            MonthlySalary: salaries,
        }