Skip to content

Instantly share code, notes, and snippets.

@NoobforAl
Last active July 5, 2023 15:21
Show Gist options
  • Save NoobforAl/7adbe9067b912e58d0756a4a41031c91 to your computer and use it in GitHub Desktop.
Save NoobforAl/7adbe9067b912e58d0756a4a41031c91 to your computer and use it in GitHub Desktop.
All Slice Method You Need Learn !
package main
import (
"fmt"
"log"
"sort"
)
type Array interface {
// use for sort Package
Len() int
Swap(i, j int)
Less(i, j int) bool
Pop() int
Copy() Slice
Revers()
Append(val int)
Index(val int) int
Remove(target int) int
}
type Slice []int
func (a Slice) Len() int { return len(a) }
func (a Slice) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a Slice) Less(i, j int) bool { return a[i] < a[j] }
func (arr *Slice) Pop() int {
if len(*arr) == 0 {
panic("array length equal zero!")
}
popVal := (*arr)[len(*arr)-1]
*arr = (*arr)[:len(*arr)-1]
return popVal
}
func (arr *Slice) Copy() Slice {
aCopy := make(Slice, len(*arr))
copy(aCopy, *arr)
return aCopy
}
func (arr Slice) Revers() {
for i, j := 0, len(arr)-1; i < j; i, j = i+1, j-1 {
arr[i], arr[j] = arr[j], arr[i]
}
}
func (arr *Slice) Append(val int) {
*arr = append(*arr, val)
}
func (arr *Slice) Index(target int) int {
for i, v := range *arr {
if v == target {
return i
}
}
return -1
}
func (arr *Slice) Remove(target int) int {
index := -1
for i, v := range *arr {
if v == target {
index = i
break
}
}
if index == -1 {
log.Panicf("Not found value ! Value: %d", target)
}
*arr = append((*arr)[:index], (*arr)[index+1:]...)
return index
}
func main() {
var arr Array = &Slice{3, 2, 1, 5, 2}
// sort array with method
// Len, Swap, Less
sort.Sort(arr)
// pop last value
// output 5
fmt.Println(arr.Pop())
// make a copy from main array
_ = arr.Copy()
// revers array
arr.Revers()
// append new Value
arr.Append(2)
// find index of value
fmt.Println(arr.Index(100))
// remove one value
// return index
fmt.Println(arr.Remove(1))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment