当前位置:网站首页>Go learning -- implementing generics based on reflection and empty interfaces

Go learning -- implementing generics based on reflection and empty interfaces

2022-07-06 07:11:00 Duck boss

One 、 Use reflection and interfaces to implement generics

package main

import (
	"fmt"
	"reflect"
)

// Define a structure 
type Container struct {
	s reflect.Value
}
// Initialize container 
func NewContainer(t reflect.Type,size int) *Container {
	if size <= 0 {
		size = 64
	}
	// Implement containers based on slice types , Initialize the underlying slice with reflection 
	return &Container{
		// Create slices 
		s : reflect.MakeSlice(reflect.SliceOf(t),0,size),
	}
}
// Add element to container 
func (c *Container) Put(val interface{}) error  {
	// Detect the element type 
	if reflect.ValueOf(val).Type() != c.s.Type().Elem() {
		return fmt.Errorf("put error: cannot put a %T into a slice of %s",val,c.s.Type().Elem())
	}
	// If the type detection is successful, it will be added to the container 
	value := reflect.Append(c.s, reflect.ValueOf(val))
	c.s = value
	return nil
}
// Read elements from container 
func (c *Container) Get(val interface{}) error  {
	// Detect the element type 
	if reflect.ValueOf(val).Kind() != reflect.Ptr || reflect.ValueOf(val).Elem().Type() != c.s.Type().Elem() {
		return fmt.Errorf("get error: needs *%s but got %T",c.s.Type().Elem(),val)
	}
	// Assign the first index position of the container to val The pointer 
	reflect.ValueOf(val).Elem().Set(c.s.Index(*(val.(*int))))
	// Delete the first index position of the container 
	slice := c.s.Slice(1, c.s.Len())
	c.s = slice
	return nil
}
func main() {
	ints := []int{1, 2, 3, 4, 5}
	// Call function initialization container 
	container := NewContainer(reflect.TypeOf(ints[0]), 16)
	// Add element to container 
	for _, n := range ints {
		if err := container.Put(n); err != nil {
			panic(err)
		}
	}
	// Read elements from container 
	num := 3
	if err := container.Get(&num); err != nil {
		panic(err)
	}
	fmt.Println(" The result is :",num)
}

 

原网站

版权声明
本文为[Duck boss]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131935507410.html