【发布时间】: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
【问题讨论】: