douwu8060 2015-09-26 14:08
浏览 25
已采纳

如何在Go中从切片结构中删除结构?

How can I remove a user defined struct from a user defined slice of user defined structs?

Something like this:

type someStruct struct {
    someOtherStruct *typeOfOtherStruct
    someInt         int
    someString      string
}

var someStructs []someStruct

func someFunc(ss someStruct, ssSlice someStructs) {
    // ..  want to remove ss from ssSlice
}

I probably should loop til I find the index, and then remove it. But how do I compare the structs?

  • 写回答

1条回答 默认 最新

  • duaiwo9093 2015-09-26 14:30
    关注

    You find the element and make a new slice minus that index.

    Example on Playground

    package main
    
    import "fmt"
    
    type someStruct struct {
        someInt    int
        someString string
    }
    
    func removeIt(ss someStruct, ssSlice []someStruct) []someStruct {
        for idx, v := range ssSlice {
            if v == ss {
                return append(ssSlice[0:idx], ssSlice[idx+1:]...)
            }
        }
        return ssSlice
    }
    func main() {
        someStructs := []someStruct{
            {1, "one"},
            {2, "two"},
            {3, "three"},
        }
        fmt.Println("Before:", someStructs)
        someStructs = removeIt(someStruct{2, "two"}, someStructs)
        fmt.Println("After:", someStructs)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?