如何在Go语言中从结构体切片中删除一个结构体?

huangapple go评论113阅读模式
英文:

How can I remove a struct from a slice of structs in Go?

问题

如何从用户定义的结构体切片中删除一个用户定义的结构体?

类似这样:

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

var someStructs []someStruct

func someFunc(ss someStruct, ssSlice someStructs) {
    // ..  想要从 ssSlice 中删除 ss
}

我可能需要循环直到找到索引,然后将其删除。但是如何比较这些结构体呢?

英文:

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

得分: 2

你找到了元素并创建了一个新的切片,减去了该索引。

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)
}
英文:

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)
}

huangapple
  • 本文由 发表于 2015年9月26日 22:08:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/32798061.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定