在一行初始化时,我可以将类的一个元素绑定到另一个元素吗?

时间:2017-12-08 09:13:50

标签: go struct initialization composite-literals

我有一个这样的类(结构):

type Question struct{
    Question string
    answerOne string
    answerTwo string
    answerCorrect string
}

我将它初始化为:

q1:=Question{
    Question:"What?",
    answerOne:"A",
    answerTwo:"B",
    answerCorrect: ? //I want this have similar value as `answerOne`
}

在启动时,我希望我的一个值与另一个值具有相似的价值。有没有办法做到这一点?

3 个答案:

答案 0 :(得分:3)

您不能仅使用文字,但可以定义函数。

func NewQuestion() *Question {
    q := &Question{
        Question:  "What?",
        answerOne: "A",
        answerTwo: "B",
    }
    q.answerCorrect = q.answerOne
    return q
}

// ...

q1 := NewQuestion()

答案 1 :(得分:1)

模拟在创建correctAnswer值后设置Question字段,您可以将正确答案存储在变量之前,并在复合文字中使用两次:

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

答案 2 :(得分:-2)

您可以创建指向struct的指针,然后将值赋给struct变量answerCorrect。最后,您可以打印valueAt结构指针。

package main

import "fmt"

// Question struct for content
type Question struct {
    Question      string
    answerOne     string
    answerTwo     string
    answerCorrect string
}

func main() {
    question := &Question{
        Question:  "What?",
        answerOne: "A",
        answerTwo: "B",
    }

    // apply condition to chose from the answer

    question.answerCorrect = question.answerTwo
    fmt.Println(*question)
}