合并多个结构体切片
侧边栏壁纸
  • 累计撰写 6 篇文章
  • 累计收到 0 条评论

合并多个结构体切片

AILA
2024-07-19 17:07 / 0 评论 / 8 阅读
package main

import "fmt"

type Rectangle struct {
    Name string
    Id   int64
}

func main() {
    var a1 []Rectangle = []Rectangle{
        {Name: "Rectangle 1", Id: 1},
        {Name: "Rectangle 2", Id: 2},
    }

    var a2 []Rectangle = []Rectangle{
        {Name: "Rectangle 3", Id: 3},
        {Name: "Rectangle 4", Id: 4},
    }

    var a3 []Rectangle = []Rectangle{
        {Name: "Rectangle 5", Id: 5},
        {Name: "Rectangle 6", Id: 6},
    }

    var a4 []Rectangle = []Rectangle{
        {Name: "Rectangle 7", Id: 7},
        {Name: "Rectangle 8", Id: 8},
    }
var  merged []Rectangle
    // 合并切片 a1, a2, a3, a4 到一个新切片 merged
    merged = append(merged,a1...)
    merged = append(merged,a2...)
    merged = append(merged,a3...)
    merged = append(merged,a4...)
    // 打印合并后的切片内容
    fmt.Println("Merged slice:")
    for _, rect := range merged {
        fmt.Printf("Name: %s, Id: %d\n", rect.Name, rect.Id)
    }
}

输出例子

Merged slice:
Name: Rectangle 1, Id: 1
Name: Rectangle 2, Id: 2
Name: Rectangle 3, Id: 3
Name: Rectangle 4, Id: 4
Name: Rectangle 5, Id: 5
Name: Rectangle 6, Id: 6
Name: Rectangle 7, Id: 7
Name: Rectangle 8, Id: 8
0

评论

博主关闭了当前页面的评论