英文:
In Go How to delete an item from slice of an Struct
问题
我有一个包含另一个结构体切片的结构体。我已经为切片的添加和删除操作添加了方法,但是添加操作有效,删除操作无效。我是Go的新手,所以我无法理解为什么切片重新赋值后没有在结构体中反映出来。
以下是我代码的简短版本。PlayGoLang链接:http://play.golang.org/p/4NnGh3Dtzw
type BatteryTest struct {
Name, LocalConf, JdkPath, SysProps, LocalconfPath string
NumberOfNodes int
}
type Server struct {
Port int
TestQueue, CompletedTests, RunningTests []BatteryTest
}
func (this *Server) AddBatteryTest(test BatteryTest) error {
this.TestQueue = append(this.TestQueue, test)
return nil
}
func (this *Server) TakeBatteryTest() error {
length := len(this.TestQueue)
if length == 0 {
fmt.Println("Len==", 0)
return errors.New("Queue is empty")
}
slice := this.TestQueue
i := len(this.TestQueue) - 1
slice = append(slice[:i], slice[i+1:]...)
return nil
}
英文:
I have struct containing a slice of another struct. I have added methods for Addition and Deletion of an item from the slice but addition is working deletion is not. I am new to Go so I am not able to understand why slice reassignment does not gets reflected in struct
Short Version of my code below. Link to PlayGoLang : http://play.golang.org/p/4NnGh3Dtzw
type BatteryTest struct {
Name, LocalConf, JdkPath, SysProps, LocalconfPath string
NumberOfNodes int
}
type Server struct {
Port int
TestQueue, CompletedTests, RunningTests []BatteryTest
}
func (this *Server) AddBatteryTest(test BatteryTest) error {
this.TestQueue = append(this.TestQueue, test)
return nil
}
func (this *Server) TakeBatteryTest() error {
length := len(this.TestQueue)
if length == 0 {
fmt.Println("Len==", 0)
return errors.New("Queue is empty")
}
slice := this.TestQueue
i := len(this.TestQueue) - 1
slice = append(slice[:i], slice[i+1:]...)
return nil
}
答案1
得分: 1
你没有将 slice
重新赋值给 this.TestQueue
。
英文:
You are not assigning slice
back to this.TestQueue
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论