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

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

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

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:

确定