【问题标题】:Golang - How to iterate through two slices at the same timeGolang - 如何同时遍历两个切片
【发布时间】:2023-02-02 17:42:31
【问题描述】:

我正在尝试编写一个接受结构的函数,其中有两个嵌套结构。我需要遍历两个嵌套结构,找到“服务”字段并删除由“-”分隔的前缀。

我已经编写了一个函数来执行我想要的操作并删除前缀,但是它由两个 for 循环组成,循环遍历两个单独的结构。他们是我以一种在一个 for 循环中循环遍历结构的方式编写此函数的方法吗?

以下是结构:

var myJson = `
{
    "ID": "hgfd5432",
    "Greeting": "Welcome!",
    "ServiceNames": [
        {
          "Service": "sevice-name-service1",
          "Version": "1.8"
        },
        {
          "Service": "sevice-name-service2",
          "Version": "1.8"
        },
        {
          "Service": "sevice-name-service3",
          "Version": "1.9"
        },
        {
          "Service": "sevice-name-service4",
          "Version": "0.6"
        }
      ],
      "Services": [
        {
          "Service": "sevice-name-service5",
          "Version": "1.8"
        }
        ],
    "BusinessUnit": "Unit 1",
    "Queue": "UK73_Advocacy_PCCT",
    "Input": "Default",
  }`

type Profile struct {
ProfileId     string        `json:"ID"`
Input         string        `json:"Input"`
ParentProfile string        `json:"ParentProfile"`
Persona       string        `json:"Persona"`
BusinessUnit  string        `json:"BusinessUnit"`
Greeting      string        `json:"Greeting"`
Queue         string        `json:"Queue"`
ServiceNames  []ServiceKey  `json:"ServiceNames"`
Services      []ServiceInfo `json:"Services"`

这是功能:

func removePrefix(inputParameters *Profile) error {

for i := 0; i < len(inputParameters.ServiceNames); i++ {
    a := strings.Split(inputParameters.ServiceNames[i].Service, "-")
    s := a[len(a)-1]
    inputParameters.ServiceNames[i].Service = s
}

for i := 0; i < len(inputParameters.Services); i++ {
    a := strings.Split(inputParameters.Services[i].Service, "-")
    s := a[len(a)-1]
    inputParameters.Services[i].Service = s
}
return nil

【问题讨论】:

    标签: arrays go struct


    【解决方案1】:

    你可以做到这一点的一种方法是,

    serviceNamesLength := len(inputParameters.ServiceNames)
    servicesLength := len(inputParameters.Services)
    
    maxLength := serviceNamesLength
    if servicesLength > maxLength {
        maxLength = servicesLength
    }
    
    for i := 0; i < maxLength; i++ {
        if i < servicesLength {
            // services stuff
        }
        if i < serviceNamesLength {
            // services names stuff
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-08-15
      • 1970-01-01
      • 1970-01-01
      • 2011-02-12
      • 2011-08-03
      • 1970-01-01
      • 2020-03-02
      • 2018-12-10
      • 1970-01-01
      相关资源
      最近更新 更多