在這段代碼中,我列印了角色,并且對于每個角色,我想撰寫附加到它的密鑰。但我不知道該怎么做。如果我i < 3
在 for 回圈中寫入,則三個鍵將列印六次,因為該roles
變數包含六個字串值。
package main
import "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)
}
}
}
給定結果
Here is the name: first name
Here is the name: first email
Here is the name: first role
Here is the name: second name
Here is the name: second email
Here is the name: second role
要求的結果
Here is the name: first name
Here is the email address: first email
Here is the job role: first role
Here is the name: second name
Here is the email address: second email
Here is the job role: second role
uj5u.com熱心網友回復:
使用整數 mod 運算子將角色索引轉換為鍵索引:
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])
}
在操場上運行示例。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/506962.html