英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论