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

▼魔方 西西 提交于 2019-12-04 05:27:25

问题


I have a class (struct) like this:

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

And I initialize it like this:

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

While initilizing I want one of my values have similar value as another one. Is there any way to do that?


回答1:


You cannot by using only literals, but you could define a function.

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

// ...

q1 := NewQuestion()



回答2:


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



回答3:


You can create a pointer to struct and then assign the value to struct variable answerCorrect. Finally you can print the valueAt struct pointer.

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


来源:https://stackoverflow.com/questions/47711031/can-i-bind-one-element-of-class-to-another-while-initializing-in-one-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!