interface to array golang

package main

import (
    "fmt"
)

type Array interface {
    Len() int
    Get(int) interface{}
    Set(int, interface{})
}

type IntArray struct {
    data []int
}

func (ia *IntArray) Len() int {
    return len(ia.data)
}

func (ia *IntArray) Get(index int) interface{} {
    return ia.data[index]
}

func (ia *IntArray) Set(index int, value interface{}) {
    ia.data[index] = value.(int)
}

func main() {
    arr := &IntArray{data: []int{1, 2, 3, 4, 5}}
    fmt.Println("Array Length:", arr.Len())
    fmt.Println("Element at index 2:", arr.Get(2))
    arr.Set(3, 10)
    fmt.Println("Modified array:", arr)
}

Explanation:

  • The Array interface is defined with three methods: Len() to get the length of the array, Get() to retrieve an element at a specific index, and Set() to set an element at a given index.
  • IntArray is a concrete type that implements the Array interface. It contains a field data which is a slice of integers ([]int).
  • Len() method returns the length of the IntArray.
  • Get() method returns the element at the specified index from the IntArray.
  • Set() method sets the element at the given index in the IntArray to the provided value after type assertion.
  • In the main() function, an IntArray instance named arr is created with initial values {1, 2, 3, 4, 5}.
  • The Len() method is used to get the length of the array and print it.
  • The Get() method is used to retrieve and print the element at index 2 of the array.
  • The Set() method is used to modify the value at index 3 to 10 and then the modified array arr is printed.