Scholli
Scholli

Reputation: 429

Go limit slice to max elements

how can i set slice max elements?

I want only 50 Elements and not over 50...

This is my Code

var result []*HistoryData
func convertHistoryResults(currenthashrate int64, online int64, offline int64, now int64) []*HistoryData {
    history := HistoryData{}
    history.CurrentHashrate = currenthashrate
    history.Online = online
    history.Offline = offline
    history.Timestamp = now
    result = append(result, &history)
    return result
}

Its working, but its pushing endless elements to it... so i have a very long slice. I want to set a maxiumum of 50. So i tried

result = append(result[:50], &history)

So that i overwrite everytime the 50th element, but idk thats not working :/

I want to cut the first element off when reaching 50th element and set 51, when cutting 1 off... so the newest is at the end and the oldest cutting off

Upvotes: 1

Views: 2623

Answers (2)

Nebril
Nebril

Reputation: 3273

This will work for you, but it will allocate memory with each append, so make sure you don't run into performance problems with this code:

i := 0
slice := []int{}
limit := 5
for i < 30 {
    if len(slice) > limit {
        slice = append(slice[1:], i)
    } else {
        slice = append(slice, i)
    }
    fmt.Println(slice)
    i++
}

Upvotes: 0

Jonathan Hall
Jonathan Hall

Reputation: 79566

There's no built-in functionality like this. You'll just need to check:

var result []*HistoryData
func convertHistoryResults(currenthashrate int64, online int64, offline int64, now int64) ([]*HistoryData, error) {
    if len(result) >= 50 {
        return nil, errors.New("result too long")
    }
    history := HistoryData{}
    history.CurrentHashrate = currenthashrate
    history.Online = online
    history.Offline = offline
    history.Timestamp = now
    result = append(result, &history)
    return result, nil
}

Upvotes: 2

Related Questions