当前位置:网站首页>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)
}
边栏推荐
- Arduino tutorial - Simon games
- (4) Web security | penetration testing | network security web site source code and related analysis
- C - Inheritance - hidden method
- Fast target recognition based on pytorch and fast RCNN
- 简单描述 MySQL 中,索引,主键,唯一索引,联合索引 的区别,对数据库的性能有什么影响(从读写两方面)
- LeetCode Algorithm 2181. 合并零之间的节点
- 【每日一题】729. 我的日程安排表 I
- Wechat brain competition answer applet_ Support the flow main belt with the latest question bank file
- UDP攻击是什么意思?UDP攻击防范措施
- 中青看点阅读新闻
猜你喜欢
kubernetes集群搭建Zabbix监控平台
Raspberry pie 3B update VIM
win10 64位装三菱PLC软件出现oleaut32.dll拒绝访问
WPF之MVVM
Short video, more and more boring?
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
Proteus -- Serial Communication parity flag mode
巴比特 | 元宇宙每日必读:中国互联网企业涌入元宇宙的群像:“只有各种求生欲,没有前瞻创新的雄心”...
LeetCode 78:子集
leetcode704. Binary search (find an element, simple, different writing)
随机推荐
ROS学习_基础
(4) Web security | penetration testing | network security web site source code and related analysis
chrome查看页面fps
idea控制台彩色日志
Uni app practical project
攻防世界 MISC中reverseMe简述
Babbitt | metauniverse daily must read: the group image of Chinese Internet enterprises pouring into metauniverse: "there are only various survival desires, and there is no ambition for forward-lookin
Entity Developer数据库应用程序的开发
How to configure GUI guide development environment
Leetcode 78: subset
The psychological process from autojs to ice fox intelligent assistance
Uncaught TypeError: Cannot red propertites of undefined(reading ‘beforeEach‘)解决方案
[server data recovery] case of offline data recovery of two hard disks of IBM server RAID5
Lesson 12 study notes 2022.02.11
CDN acceleration and cracking anti-theft chain function
巴比特 | 元宇宙每日必读:中国互联网企业涌入元宇宙的群像:“只有各种求生欲,没有前瞻创新的雄心”...
Interface automation test framework: pytest+allure+excel
Kubernetes cluster builds ZABBIX monitoring platform
【服务器数据恢复】IBM服务器raid5两块硬盘离线数据恢复案例
PCL realizes frame selection and clipping point cloud