循环访问 golang 中的动态嵌套结构

我创建了一个动态结构来取消JSON的元帅。结构看起来像:


type Partition struct {

    DiskName      string      `json:"disk_name"`

    Mountpoint    interface{} `json:"mountpoint,omitempty"`

    Size          string      `json:"size"`

    Fstype        string      `json:"fstype,omitempty"`

    SubPartitions bool        `json:"sub_partitions"`

    Partitions    []Partition `json:"partitions,omitempty"`

}


type NasInfo struct {

    Blockdevices []struct {

        DiskName   string      `json:"disk_name"`

        Mountpoint interface{} `json:"mountpoint,omitempty"`

        Size       string      `json:"size"`

        Fstype     string      `json:"fstype,omitempty"`

        Partitions []Partition `json:"partitions,omitempty"`

    } `json:"blockdevices"`

}

现在,块设备内部可以有许多分区,一个分区中可以有多个子分区。我想手动为分区结构中的字段赋值。我怎么能这样做。如何迭代每个分区和子分区并为其分配手动值。有没有办法做到这一点?


当前使用这个 :


    totalPartitions := len(diskInfo.Blockdevices[0].Partitions)

    if totalPartitions > 0 {

        for i := 0; i < totalPartitions; i++ {

            if diskInfo.Blockdevices[0].Partitions[i].Partitions != nil {

                diskInfo.Blockdevices[0].Partitions[i].SubPartitions = true

            } else {

                diskInfo.Blockdevices[0].Partitions[i].SubPartitions = false

            }

        }

    }

但它只能处理 1 个分区和一个子分区。有没有办法迭代每个并为其分配值?


陪伴而非守候
浏览 136回答 2
2回答

守着一只汪

编写函数func markSubPartition(p *Partition) {if len(p.Partitions) > 0 {&nbsp; &nbsp; p.SubPartitions = true&nbsp; &nbsp; for _, part := range p.Partitions {&nbsp; &nbsp; &nbsp; &nbsp; markSubPartition(part)&nbsp; &nbsp; }} else {&nbsp; &nbsp; p.SubPartitions = false}}并像这样循环使用块设备for _, part := range diskInfo.Blockdevices[0].Partitions {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; markSubPartition(part)}还需要更改您的结构更改分区字段:分区[]*分区希望它有帮助,谢谢!json:"partitions,omitempty"

阿晨1998

由于该标志与 耦合,因此一种选择是删除该字段,并添加一个计算此值的方法:SubPartitionsPartitionsSubPartitionsfunc (p *Partition) HasSubPartitions() bool {&nbsp; &nbsp; // note : to check if a slice is empty or not, it is advised to look at&nbsp; &nbsp; // 'len(slice)' rather than nil (it is possible to have a non-nil pointer&nbsp; &nbsp; // to a 0 length slice)&nbsp; &nbsp; return len(p.Partitions) > 0&nbsp;&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go