Home > Blockchain >  How to copy one struct to nested struct having same fields
How to copy one struct to nested struct having same fields

Time:10-07

I need to automate creation of story JIRA using golang. For this I can mapped required nested json to golang and I am able to create story also. Now I want to try with simple input as json and copy to nested struct having same fields.

Ex. I have input json like

{
  "project": "cdo",
  "summary": "sample test story",
  "issueType": "Story",
  "userStory" : "this is jira",
  "assignee": "pradnya.shinde",
  "teamOwner" : "TEAM-59",
  "productOwner": "alex.anguiano"
}

I have mapped above json in golang struct like

type InputJson struct {
    Project      string `json:"project"`
    Summary      string `json:"summary"`
    Issuetype    string `json:"issueType"`
    UserStory    string `json:"userStory"`
    Assignee     string `json:"assignee"`
    TeamOwner    string `json:"teamOwner"`
    ProductOwner string `json:"productOwner"`
}

I want to copy this struct to another nested struct. Nested struct is like

type JiraCreateStory struct {
    Fields struct {
        Project struct {
            Key string
        }
        Summary   string
        Issuetype struct {
            Name string
        }
        UserStory string
        Assignee  struct {
            Name string
        }
        ProductOwner struct {
            Name string
        }
        TeamOwner string
    }
}

Can anyone suggest how can I copy it with simple code?

CodePudding user response:

Declare types for all structs:

type JiraCreateStory struct {
    Fields Fields
}

type Fields struct {
    Project      Project
    Summary      string
    Issuetype    Issuetype
    UserStory    string
    Assignee     Assignee
    ProductOwner ProductOwner
}

type Project struct { Key string }
type Issuetype struct { Name string }
type Assignee struct { Name string }
type ProductOwner struct { Name string }

Create a JiraCreateStory using a composite literal:

x := JiraCreateStory{Fields: Fields{
    Project:      Project{Key: src.Project},
    Summary:      src.Summary,
    Issuetype:    Issuetype{Name: src.Issuetype},
    UserStory:    src.UserStory,
    Assignee:     Assignee{Name: src.Assignee},
    ProductOwner: ProductOwner{Name: src.ProductOwner},
}}
  • Related