2015-12-29 61 views
1

考慮以下幾點:構建從片陣列圍棋

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

回答

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

0

我會創建一個包含您所需要的信息一個位置的結構:

type Position struct { 
PositionTitle   string 
PositionRelationships string 
PositionInstitution string 
} 

並創建這些結構的數組(或切片)遍歷他們。這是一個工作示例:http://play.golang.org/p/s02zfeNJ63