如何将 if 语句添加到结构初始化

How to add an if statement to a struct initialization

我正在尝试在嵌套结构中添加 if 语句,每当我尝试构建时,我都会得到:syntax error: unexpected if, expecting expression.

我找到了一个简单的代码来展示我正在尝试做的事情:

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,
            },
        },
    }

而且我发现这可能是通过预处理器完成的,我对此一无所知。

请注意,该结构是从我原始代码中的另一个包导入的,我无法更改它的声明和使用方式。

您不能将逻辑内联到结构中。您必须在变量声明之外执行此操作。但这很容易。例如:

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,
    }