在此代碼中,我打印了角色,并且對于每個角色,我都想寫下附加到它的密鑰。但我不知道該怎么做。如果我i < 3在 for 循環(huán)中寫入,那么這三個鍵將被打印六次,因為該roles變量包含六個字符串值。package mainimport "fmt"func main() { roles := []string{"first name", "first email", "first role", "second name", "second email", "second role"} keys := [3]string{"name", "email address", "job role"} for _, data := range roles { for i := 0; i < 1; i++ { fmt.Println("Here is the "+keys[i]+":", data) } }}給出的結(jié)果Here is the name: first nameHere is the name: first emailHere is the name: first roleHere is the name: second nameHere is the name: second emailHere is the name: second role要求的結(jié)果Here is the name: first nameHere is the email address: first emailHere is the job role: first roleHere is the name: second nameHere is the email address: second emailHere is the job role: second role
1 回答

慕雪6442864
TA貢獻1812條經(jīng)驗 獲得超5個贊
使用整數(shù) mod 運算符將角色索引轉(zhuǎn)換為鍵索引:
roles := []string{"first name", "first email", "first role", "second name", "second email", "second role"}
keys := []string{"name", "email address", "job role"}
// i is index into roles
for i := range roles {
// j is index into keys
j := i % len(keys)
// Print blank line between groups.
if j == 0 && i > 0 {
fmt.Println()
}
fmt.Printf("Here is the %s: %s\n", keys[j], roles[i])
}
- 1 回答
- 0 關(guān)注
- 135 瀏覽
添加回答
舉報
0/150
提交
取消