英文:
Construct Array from Slices in Go
问题
给定以下代码:
var positionTitles []string
var positionRelationships []string
var positionInstitutions []string
positionTitles = ["Director" "Provost" "Assistant Provost"]
positionRelationships = ["Tenured Professor" "Lecturer" "Adjunct Professor"]
positionInstitutions = ["UCSC" "UCB" "USC"]
如何构建一个类似下面的数组:
Positions :=
[{
PositionTitle: "Director",
PositionRelationships: "Tenured Professor",
PositionInstitution: "UCSC",
},
{
PositionTitle: "Provost",
PositionRelationships: "Lecturer",
PositionInstitution: "UCB",
},
{
PositionTitle: "Assistant Provost",
PositionRelationships: "Adjunct Professor",
PositionInstitution: "USC",
}]
目标是遍历 Positions。
我已经在 Go Playground 上开始了一个示例:
http://play.golang.org/p/za_9U7eHHT
英文:
Given the following:
var positionTitles []string
var positionRelationships []string
var positionInstitutions []string
positionTitles = ["Director" "Provost" "Assistant Provost"]
positionRelationships = ["Tenured Professor" "Lecturer" "Adjunct Professor"]
positionInstitutions = ["UCSC" "UCB" "USC"]
How would I construct an array that looks like such:
Positions :=
[{
PositionTitle: "Director",
PositionRelationships: "Tenured Professor",
PositionInstitution: "UCSC",
},
{
PositionTitle: "Provost",
PositionRelationships: "Lecturer",
PositionInstitution: "UCB",
},
{
PositionTitle: "Assistant Provost",
PositionRelationships: "Adjunct Professor",
PositionInstitution: "USC",
}]
The goal is to iterate over the Positions.
Go Playground I've started:
http://play.golang.org/p/za_9U7eHHT
答案1
得分: 2
你可以创建一个类型来保存所有的片段,并迭代这些片段,例如:
type Position struct {
Title, Relationship, Institution string
}
positions := make([]Position, len(positionTitles))
for i, title := range positionTitles {
positions[i] = Position{
Title: title,
Relationship: positionRelationships[i],
Institution: positionInstitutions[i],
}
}
然而,如果你只需要进行迭代,不需要创建一个类型。可以参考for
循环的主体部分。
链接:https://play.golang.org/p/1P604WWRGd
英文:
You can create a type that would hold all the pieces and iterate over the slices such that
type Position struct {
Title, Relationship, Institution string
}
positions := make([]Position, len(positionTitles))
for i, title := range positionTitles {
positions[i] = Position{
Title: title,
Relationship: positionRelationships[i],
Institution: positionInstitutions[i],
}
}
However, if you need it only to iterate, you don't need to create a type. See body of the for
.
答案2
得分: 0
我会创建一个包含所需信息的Position结构体:
type Position struct {
PositionTitle string
PositionRelationships string
PositionInstitution string
}
然后创建一个该结构体的数组(或切片),以便对它们进行迭代。这里有一个可工作的示例:http://play.golang.org/p/s02zfeNJ63
英文:
I would create a Position struct containing the informations you need :
type Position struct {
PositionTitle string
PositionRelationships string
PositionInstitution string
}
and create an array (or slice) of those structs to iterate over them. Here is a working example : http://play.golang.org/p/s02zfeNJ63
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论