我是 GoLang 的新手,来自 Node。游戏有点晚了(绝对不起作用),需要一些帮助来理解方法,也许只是理解......
我想从数组中的一堆结构中省略一个项目。
lo.Map(twelveShuffledQuestions, func(q StaticQuestion) {
return &StaticQuestionMinusCorrectAnswer{
QuestionId: q.QuestionId,
QuestionType: q.QuestionType,
QuestionText: q.QuestionText,
PotentialAnswers: q.PotentialAnswers,
Image: q.Image,
}
})
所有这一切基本上都是在展示一种模式,我将如何在节点中处理它(在lo的帮助下) - 不,这不会编译,因为它无法推断类型args。
就这里的数据结构而言,
twelveShuffledQuestions
是JSON支持的,这意味着它是导入然后编组的:
jsonFile, err := os.Open("questions.json")
if err != nil {
panic(err)
}
defer jsonFile.Close()
byteValue, _ := io.ReadAll(jsonFile)
localQuestionsToCheckAgainst := []StaticQuestion{}
json.Unmarshal([]byte(byteValue), &localQuestionsToCheckAgainst)
我的问题是如何从数组中的结构中实现我想要的字段映射?
循环原来的问题。 创建一个没有答案的问题并附加到结果中。
byteValue, _ := os.ReadFile("questions.json")
var localQuestionsToCheckAgainst []StaticQuestion
json.Unmarshal(byteValue, &localQuestionsToCheckAgainst)
var result []*StaticQuestionMinusCorrectAnswer
for _, q := range localQuestionsToCheckAgainst {
result = append(result, &StaticQuestionMinusCorrectAnswer{
QuestionId: q.QuestionId,
QuestionType: q.QuestionType,
QuestionText: q.QuestionText,
PotentialAnswers: q.PotentialAnswers,
Image: q.Image,
})
}