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

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

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

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

在初始化时,我希望我的一个值与另一个值具有相似的值。有什么办法吗?

你不能只使用文字,但你可以定义一个函数。

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

// ...

q1 := NewQuestion()

您可以创建一个指向结构的指针,然后将值赋给结构变量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)
}

类似于在创建 Question 值后设置 correctAnswer 字段,您可以先将正确答案存储在变量中,并在复合文字中使用它两次:

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