如何在Go语言中让键与对应值匹配并分组打印?
解决Go中roles切片与keys数组的对应打印问题
你的核心问题是roles切片按每3个元素为一组对应keys数组的三个键,但原代码逐个遍历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"} // 计算用户信息的组数(每组对应一组keys) groupNum := len(roles) / len(keys) for group := 0; group < groupNum; group++ { // 遍历当前组的每个键值对 for idx := 0; idx < len(keys); idx++ { // 计算当前元素在roles中的位置:组序号*每组元素数 + 键的索引 roleIndex := group*len(keys) + idx fmt.Printf("Here is the %s: %s\n", keys[idx], roles[roleIndex]) } // 组与组之间添加空行(最后一组不添加) if group != groupNum-1 { fmt.Println() } } }
代码逻辑说明
- 先通过
len(roles)/len(keys)确定一共有多少组用户信息(这里是2组) - 外层循环控制组的遍历,内层循环对应
keys的每个键 - 用
group*len(keys)+idx精准定位roles中当前组的对应元素,确保每个键匹配正确的角色信息 - 组之间添加空行,和你期望的输出格式完全一致
运行这段代码后,输出就是你想要的结果:
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
如果后续roles的组数增加(比如新增第三组信息),这段代码也能自动适配,不需要修改循环条件。
内容的提问来源于stack exchange,提问作者Veins Tree
相关产品推荐
相关产品推荐

