猿问

在 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",

  }]

目标是迭代位置。


去游乐场我已经开始了:http : //play.golang.org/p/za_9U7eHHT


翻翻过去那场雪
浏览 161回答 2
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

DIEA

我会创建一个 Position 结构,其中包含您需要的信息:type Position struct {PositionTitle         stringPositionRelationships stringPositionInstitution   string}并创建这些结构的数组(或切片)以迭代它们。这是一个工作示例:http : //play.golang.org/p/s02zfeNJ63
随时随地看视频慕课网APP

相关分类

Go
我要回答