简体   繁体   English

从Go中的切片构造数组

[英]Construct Array from Slices in Go

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 我开始的游乐场: http : //play.golang.org/p/za_9U7eHHT

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 . 见的身体for

https://play.golang.org/p/1P604WWRGd https://play.golang.org/p/1P604WWRGd

I would create a Position struct containing the informations you need : 我将创建一个Position结构,其中包含您需要的信息:

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 这是一个工作示例: http : //play.golang.org/p/s02zfeNJ63

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM