在一行中初始化时,可以将类的一个元素绑定到另一个元素吗? [英] Can I bind one element of class to another while initializing in one line?

查看:63
本文介绍了在一行中初始化时,可以将类的一个元素绑定到另一个元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a class (struct) like this:

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

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

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

推荐答案

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

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

这篇关于在一行中初始化时,可以将类的一个元素绑定到另一个元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆