slice.go 1023 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package slice
  2. type Slice[T any] []T
  3. func New[T any](initCap int) Slice[T] {
  4. return make(Slice[T], 0, initCap)
  5. }
  6. func (s *Slice[T]) Append(t T) {
  7. *s = append(*s, t)
  8. }
  9. func (s *Slice[T]) AppendFront(t T) {
  10. *s = append([]T{t}, *s...)
  11. }
  12. func (s *Slice[T]) Get(index int) (t T, ok bool) {
  13. if index < 0 || index >= s.Len() {
  14. return
  15. }
  16. t = (*s)[index]
  17. ok = true
  18. return
  19. }
  20. func (s *Slice[T]) Set(index int, t T) (old T, ok bool) {
  21. if index < 0 || index >= s.Len() {
  22. return
  23. }
  24. old = (*s)[index]
  25. (*s)[index] = t
  26. ok = true
  27. return
  28. }
  29. func (s *Slice[T]) Delete(index int) (t T, ok bool) {
  30. if index < 0 || index >= s.Len() {
  31. return
  32. }
  33. t = (*s)[index]
  34. *s = append((*s)[:index], (*s)[index+1:]...)
  35. ok = true
  36. return
  37. }
  38. func (s *Slice[T]) Swap(i, j int) {
  39. if i < 0 || j < 0 || i >= s.Len() || j >= s.Len() {
  40. return
  41. }
  42. (*s)[i], (*s)[j] = (*s)[j], (*s)[i]
  43. }
  44. func (s *Slice[T]) Len() int {
  45. return len(*s)
  46. }
  47. func (s *Slice[T]) Cap() int {
  48. return cap(*s)
  49. }
  50. func (s *Slice[T]) Clear() {
  51. *s = Slice[T]{}
  52. }