如何在结构初始化中添加if语句

布鲁斯:

我试图在嵌套结构中添加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:     "[email protected]",
        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,
            },
        },
    }

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

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

lim

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

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:     "[email protected]",
        Age:       25,
        // And here include them in the variable declaration
        MonthlySalary: salaries,
    }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章