Can I bind one element of class to another while initializing in one line?

后端 未结 3 888
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-24 08:27

I have a class (struct) like this:

type Question struct{
    Question string
    answerOne string
    answerTwo string
    answerCorrect string
}
3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-24 08:51

    Analog to setting the correctAnswer field after creating the Question value, you can store the correct answer in a variable prior, and use that twice in the composite literal:

    answerA := "A"
    q := Question{
        Question:      "What?",
        answerOne:     answerA,
        answerTwo:     "B",
        answerCorrect: answerA,
    }
    

提交回复
热议问题