Golang中如何向嵌套结构体添加新项

Golang中如何向嵌套结构体添加新项 我的结构体如下:

type WorkI struct {
	Create Create `json:"create"`
}

type Create struct {
	TicketNoteRequest TicketNoteRequest `json:"ticketNoteRequest"`
}

type TicketNoteRequest struct {
	Author         interface{}   `json:"author"`
	Text           string        `json:"text"`
	Attachments    []Attachments `json:"attachments"`
	AdditionalData []Ad          `json:"additionalData"`
}

type Attachments struct {
	Author         interface{} `json:"author"`
	Name           string      `json:"name"`
	DocumentLink   interface{} `json:"documentLink"`
	Attachment     Attachment  `json:"attachment"`
	Content        string      `json:"content"`
	AdditionalData interface{} `json:"additionalData"`
}

type Attachment struct {
	AttachmentSummary AttachmentSummary `json:"attachmentSummary"`
}

type AttachmentSummary struct {
	Name          string      `json:"name"`
	ContentType   interface{} `json:"contentType"`
	ContentID     interface{} `json:"contentId"`
	ContentLength int         `json:"contentLength"`
}

我这样初始化:

data = WorkI{
			Create: Create{
				TicketNoteRequest: TicketNoteRequest{
					Attachments: []Attachments{
						{
							Name: t.Num1.FileName,
							Attachment: Attachment{
								AttachmentSummary: AttachmentSummary{
									Name: t.Num1.Content,
								},
							},
							Content: "123213213213213",
						},
					},
				},
			},
		}

我想知道如何在Attachments中添加另一个附件,而不需要重新初始化整个结构体?

谢谢


更多关于Golang中如何向嵌套结构体添加新项的实战教程也可以访问 https://www.itying.com/category-94-b0.html

2 回复

你好

c.Attachments = append(c.Attachments, newAttachment)

其中 newAttachment 是您想要添加到现有附件中的一个附件

更多关于Golang中如何向嵌套结构体添加新项的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Go语言中,要向嵌套结构体的切片字段(如Attachments)添加新项,可以直接访问该切片并使用append函数。以下是具体实现:

// 假设已有初始化的data变量
newAttachment := Attachments{
    Name: "new_file.txt",
    Attachment: Attachment{
        AttachmentSummary: AttachmentSummary{
            Name: "new_content",
        },
    },
    Content: "new_content_data",
}

// 向Attachments切片添加新项
data.Create.TicketNoteRequest.Attachments = append(
    data.Create.TicketNoteRequest.Attachments, 
    newAttachment,
)

如果需要在现有附件后追加多个附件:

additionalAttachments := []Attachments{
    {
        Name: "file2.txt",
        Attachment: Attachment{
            AttachmentSummary: AttachmentSummary{
                Name: "content2",
            },
        },
        Content: "content_data_2",
    },
    {
        Name: "file3.txt",
        Attachment: Attachment{
            AttachmentSummary: AttachmentSummary{
                Name: "content3",
            },
        },
        Content: "content_data_3",
    },
}

data.Create.TicketNoteRequest.Attachments = append(
    data.Create.TicketNoteRequest.Attachments, 
    additionalAttachments...,
)

这种方法直接修改了原始结构体中的切片,无需重新初始化整个结构体。切片在Go中是通过引用传递的,因此对切片的修改会反映在原始结构体中。

回到顶部