[go skill] After the slices of the structure type are sorted from small to large, specific multiple indexes are eliminated

Table of contents

After the slices of the structure type are sorted from small to large, specific multiple indexes are eliminated


After the slices of the structure type are sorted from small to large, specific multiple indexes are eliminated

To delete elements at multiple indices, we can use a loop statement to achieve it. The specific implementation process is as follows:

package main

import (
    "fmt"
    "sort"
)

type Person struct {
    Name   string
    Score  int
}

func main() {
    persons := []Person{
        {Name: "Alice", Score: 80},
        {Name: "Bob", Score: 90},
        {Name: "Charlie", Score: 72},
        {Name: "David", Score: 85},
        {Name: "Eva", Score: 92},
    }

    // 要删除的所有索引
    indexes := []int{1, 3}

    // 将索引从小到大排序
    sort.Ints(indexes)

    fmt.Println("Before filtering:", persons)

    for i := len(indexes) - 1; i >= 0; i-- {
        index := indexes[i]
        persons = append(persons[:index], persons[index+1:]...)
    }

    fmt.Println("After filtering:", persons)
}

In the sample code above, we first define a slice that contains multiple Personstructs persons. Then, we define a list of indices of all elements to remove indexes. Then, we call sort.Ints()the function to sort these indexes from small to large.

In the loop statement, we traverse all the indexes to be deleted, remove the elements at the corresponding indexes in the slice one by one, finally get the modified slice, and output the result.

Guess you like

Origin blog.csdn.net/fanjufei123456/article/details/131175649