Created
February 26, 2025 20:20
-
-
Save saginadir/296378051bab572aeb47ccf520298d67 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"fmt" | |
"reflect" | |
) | |
// HeterogeneousList represents a list that can hold any type of data | |
type HeterogeneousList struct { | |
elements []any // Using 'any' (equivalent to interface{} in older Go versions) for heterogeneous data | |
} | |
// NewHeterogeneousList creates and returns a new HeterogeneousList | |
func NewHeterogeneousList() *HeterogeneousList { | |
return &HeterogeneousList{ | |
elements: make([]any, 0), | |
} | |
} | |
// Add adds an element of any type to the list | |
func (hl *HeterogeneousList) Add(element any) { | |
hl.elements = append(hl.elements, element) | |
} | |
// Get retrieves an element and its type at the specified index | |
// Returns the element (as any), its reflect.Type, and an error if the index is out of bounds | |
func (hl *HeterogeneousList) Get(index int) (any, reflect.Type, error) { | |
if index < 0 || index >= len(hl.elements) { | |
return nil, nil, errors.New("index out of bounds") | |
} | |
element := hl.elements[index] | |
return element, reflect.TypeOf(element), nil | |
} | |
// Size returns the number of elements in the list | |
func (hl *HeterogeneousList) Size() int { | |
return len(hl.elements) | |
} | |
// Example usage in main | |
func main() { | |
// Create a new heterogeneous list | |
list := NewHeterogeneousList() | |
// Add different types of data | |
list.Add(42) // Integer | |
list.Add("Hello, Go!") // String | |
list.Add(3.14) // Float | |
list.Add(true) // Boolean | |
list.Add(struct{ Name string }{Name: "Struct"}) // Struct | |
// Print the size of the list | |
fmt.Printf("List size: %d\n", list.Size()) | |
// Retrieve and print elements with their types | |
for i := 0; i < list.Size(); i++ { | |
element, elementType, err := list.Get(i) | |
if err != nil { | |
fmt.Printf("Error at index %d: %v\n", i, err) | |
continue | |
} | |
// Print the element and its type | |
fmt.Printf("Index %d: Value = %v, Type = %s\n", i, element, elementType) | |
} | |
// Example of error handling for out-of-bounds access | |
_, _, err := list.Get(10) | |
if err != nil { | |
fmt.Printf("Error: %v\n", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment