当前位置:网站首页>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)
}
边栏推荐
猜你喜欢
![[advanced software testing step 1] basic knowledge of automated testing](/img/3d/f83f792e24efc39f00c0dc33936ce8.png)
[advanced software testing step 1] basic knowledge of automated testing

leetcode1020. 飞地的数量(中等)

Upgraded wechat tool applet source code for mobile phone detection - supports a variety of main traffic modes

win10 64位装三菱PLC软件出现oleaut32.dll拒绝访问

1091: two or three things in childhood (multi instance test)

leetcode6109. 知道秘密的人数(中等,周赛)

【服务器数据恢复】IBM服务器raid5两块硬盘离线数据恢复案例

作者已死?AI正用藝術征服人類

C language_ Double create, pre insert, post insert, traverse, delete

19.段页结合的实际内存管理
随机推荐
3. Business and load balancing of high architecture
树莓派3B更新vim
SSM learning
mysql如何合并数据
UDP攻击是什么意思?UDP攻击防范措施
MVVM of WPF
Path analysis model
【Hot100】739. Daily temperature
呆错图床系统源码图片CDN加速与破解防盗链功能
Lesson 12 study notes 2022.02.11
L'auteur est mort? Ai utilise l'art pour conquérir l'humanité
Raspberry pie serial port login and SSH login methods
开源的网易云音乐API项目都是怎么实现的?
前缀和数组系列
Fast target recognition based on pytorch and fast RCNN
#systemverilog# 可綜合模型的結構總結
RichView TRVStyle 模板样式的设置与使用
C - Inheritance - polymorphism - virtual function member (lower)
Week6 weekly report
Wechat brain competition answer applet_ Support the flow main belt with the latest question bank file