It's certainly not necessary to iterate the list twice, though the below method uses more memory:
func (input Input) Sort() *[]string {
if input.Media == nil || LimitedAmountItems <= 0 {
return new([]string)
}
isPrinciple = make([]string, 0, LimitedAmountItems
var notPrinciple []string
for _, media := range input.Media {
if media.IsPrincipal {
isPrinciple = append(isPrinciple, media.URL)
} else {
notPrinciple = append(notPrinciple, media.URL)
}
if len(isPrinciple) >= LimitedAmountItems {
return &isPrinciple
}
}
items := append(isPrinciple, notPrinciple[:LimitedAmountItems-len(isPrinciple)]...)
return &items
}
This iterates the list only once, while maintaining the same behavior, though it may use some additional memory for the second holding slice (however it should also have fewer allocations as it preallocates one slice).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…