In Go How to delete an item from slice of an Struct

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

In Go How to delete an item from slice of an Struct

问题

我有一个包含另一个结构体切片的结构体。我已经为切片的添加和删除操作添加了方法,但是添加操作有效,删除操作无效。我是Go的新手,所以我无法理解为什么切片重新赋值后没有在结构体中反映出来。

以下是我代码的简短版本。PlayGoLang链接:http://play.golang.org/p/4NnGh3Dtzw

  1. type BatteryTest struct {
  2. Name, LocalConf, JdkPath, SysProps, LocalconfPath string
  3. NumberOfNodes int
  4. }
  5. type Server struct {
  6. Port int
  7. TestQueue, CompletedTests, RunningTests []BatteryTest
  8. }
  9. func (this *Server) AddBatteryTest(test BatteryTest) error {
  10. this.TestQueue = append(this.TestQueue, test)
  11. return nil
  12. }
  13. func (this *Server) TakeBatteryTest() error {
  14. length := len(this.TestQueue)
  15. if length == 0 {
  16. fmt.Println("Len==", 0)
  17. return errors.New("Queue is empty")
  18. }
  19. slice := this.TestQueue
  20. i := len(this.TestQueue) - 1
  21. slice = append(slice[:i], slice[i+1:]...)
  22. return nil
  23. }
英文:

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

  1. type BatteryTest struct {
  2. Name, LocalConf, JdkPath, SysProps, LocalconfPath string
  3. NumberOfNodes int
  4. }
  5. type Server struct {
  6. Port int
  7. TestQueue, CompletedTests, RunningTests []BatteryTest
  8. }
  9. func (this *Server) AddBatteryTest(test BatteryTest) error {
  10. this.TestQueue = append(this.TestQueue, test)
  11. return nil
  12. }
  13. func (this *Server) TakeBatteryTest() error {
  14. length := len(this.TestQueue)
  15. if length == 0 {
  16. fmt.Println("Len==", 0)
  17. return errors.New("Queue is empty")
  18. }
  19. slice := this.TestQueue
  20. i := len(this.TestQueue) - 1
  21. slice = append(slice[:i], slice[i+1:]...)
  22. return nil
  23. }

答案1

得分: 1

你没有将 slice 重新赋值给 this.TestQueue

英文:

You are not assigning slice back to this.TestQueue

huangapple
  • 本文由 发表于 2015年2月8日 01:42:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/28385311.html
匿名

发表评论

匿名网友

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

确定