Friday, March 4, 2022

Golang: Dynamic Array sample

sample code of dynamic array in Golang.



 // You can edit this code!

// Click here and start typing.

package main


import "fmt"


type Arr struct {

arr []string

}


type SError struct {

code    int32

message string

}


func main() {

newArr := &Arr{arr: []string{"a", "b", "c", "d", "e", "f", "g"}}


fmt.Println(newArr.size())


str, err := newArr.get(8)

if err != nil {

fmt.Println(err)

} else {

fmt.Printf("item value = %s", str)

}


newArr.set(10, "asssss")


err = newArr.removeAt(10)

if err != nil {

fmt.Println(err)

} else {

fmt.Printf("removed with index :  %v", newArr.arr)

}


err = newArr.remove("fasd")

if err != nil {

fmt.Println(err)

} else {

fmt.Printf("remove with string: %v", newArr.arr)

}

}


func (arr *Arr) get(i int) (string, *SError) {

if i > arr.size()-1 || i < 0 {

return "", &SError{code: 5, message: fmt.Sprintf("Error accesing index %d from array.", i)}

}


return arr.arr[i], nil

}


func (arr *Arr) set(i int, v string) *SError {

if i > arr.size()-1 || i < 0 {

return &SError{code: 4, message: fmt.Sprintf("%d not exists in the array.", i)}

}


arr.arr[i] = v

return nil

}


func (arr *Arr) add(v string) {

arr.arr = append(arr.arr, v)

}


func (arr *Arr) removeAt(i int) *SError {

if i > arr.size()-1 || i < 0 {

return &SError{code: 3, message: fmt.Sprintf("Error removing index %d from array.", i)}

}

arr.arr = append(arr.arr[:i], arr.arr[i+1:arr.size()]...)

return nil

}


func (arr *Arr) remove(v string) *SError {


if arr.size() == 0 {

return &SError{code: 1, message: "Array is empty"}

}


// find the index

for k, val := range arr.arr {

if val == v {

// and removeAt

arr.removeAt(k)

return nil

}

}


return &SError{code: 2, message: fmt.Sprintf("Error removing %s from array.", v)}

}


func (arr *Arr) size() int {

return len(arr.arr)

}


No comments:

Post a Comment