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, andSet()
to set an element at a given index. IntArray
is a concrete type that implements theArray
interface. It contains a fielddata
which is a slice of integers ([]int
).Len()
method returns the length of theIntArray
.Get()
method returns the element at the specified index from theIntArray
.Set()
method sets the element at the given index in theIntArray
to the provided value after type assertion.- In the
main()
function, anIntArray
instance namedarr
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 arrayarr
is printed.