You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Go语言中迭代打印多组values变量数据?

解决Go语言多组数据批量打印的问题

你不需要为每一组values重复编写循环,只需要把多组数据整合到一个集合里,再提取通用的打印逻辑即可。以下是具体的修改方案:

1. 重构数据结构

把分散的values1、values2放到一个切片的切片中,这样可以统一遍历所有数据组:

valuesGroups := [][]string{
    {"samename", "email one", "job role one"},
    {"samename", "email two", "job role two"},
    // 可以继续添加更多组
}

2. 提取通用打印函数

把打印单组数据的逻辑封装成函数,避免重复代码:

func printGroup(keys []string, values []string) {
    for i := range keys {
        fmt.Printf("Here is the %s: %s\n", keys[i], values[i])
    }
}

3. 调整主逻辑

验证姓名通过后,遍历所有数据组,逐个调用打印函数,组之间添加空行分隔:

完整修改后的代码:

package main

import "fmt"

func printGroup(keys []string, values []string) {
    for i := range keys {
        fmt.Printf("Here is the %s: %s\n", keys[i], values[i])
    }
}

func main() {
    var name string
    keys := []string{"name", "email address", "job role"}
    valuesGroups := [][]string{
        {"samename", "email one", "job role one"},
        {"samename", "email two", "job role two"},
        // 可按需添加更多数据组
    }

    for {
        fmt.Printf("Enter your name: ")
        fmt.Scanln(&name)
        fmt.Println()

        // 检查姓名是否存在于任意数据组中
        matched := false
        for _, group := range valuesGroups {
            if name == group[0] {
                matched = true
                break
            }
        }

        if matched {
            // 遍历打印所有匹配的组
            for idx, group := range valuesGroups {
                if group[0] == name {
                    if idx > 0 {
                        fmt.Println() // 组之间添加空行分隔
                    }
                    printGroup(keys, group)
                }
            }
            break
        } else {
            fmt.Println("Name is not found. Try again!")
        }
    }
}

关键说明

  • 用[][]string存储多组数据,后续新增数据组只需在切片里追加,无需修改循环逻辑
  • 封装printGroup函数后,打印逻辑只需维护一处,减少冗余代码
  • 先统一检查姓名是否匹配,再遍历打印所有符合条件的组,逻辑更清晰
  • 通过判断索引idx > 0添加组间空行,避免开头或结尾出现多余空行

运行后输入samename,就能得到你想要的输出效果:

Enter your name: samename

Here is the name: samename
Here is the email address: email one
Here is the job role: job role one

Here is the name: samename
Here is the email address: email two
Here is the job role: job role two

内容的提问来源于stack exchange,提问作者Veins Tree

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 09:45:41