当前位置:网站首页>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)
}
边栏推荐
- Lesson 12 study notes 2022.02.11
- Interface automation test framework: pytest+allure+excel
- Kubernetes cluster builds ZABBIX monitoring platform
- After sharing the clone remote project, NPM install reports an error - CB () never called! This is an error with npm itself.
- Visitor tweets about how you can layout the metauniverse
- Top test sharing: if you want to change careers, you must consider these issues clearly!
- ROS learning_ Basics
- chrome查看页面fps
- Chrome view page FPS
- Practical guidance for interface automation testing (Part I): what preparations should be made for interface automation
猜你喜欢
Raspberry pie 3B update VIM
1189. Maximum number of "balloons"
微信公众号无限回调授权系统源码 全网首发
Cif10 actual combat (resnet18)
C language_ Double create, pre insert, post insert, traverse, delete
1091: two or three things in childhood (multi instance test)
微信脑力比拼答题小程序_支持流量主带最新题库文件
Raspberry pie serial port login and SSH login methods
(4) Web security | penetration testing | network security web site source code and related analysis
Leetcode59. spiral matrix II (medium)
随机推荐
Solution to the problem of breakthrough in OWASP juice shop shooting range
【Hot100】739. 每日温度
CDN acceleration and cracking anti-theft chain function
Visitor tweets about how you can layout the metauniverse
leetcode6109. 知道秘密的人数(中等,周赛)
Simple use of JWT
hydra常用命令
JDBC学习笔记
Hydra common commands
MPLS experiment
Résumé de la structure du modèle synthétisable
Markdown 中设置图片图注
win10 64位装三菱PLC软件出现oleaut32.dll拒绝访问
How to find a medical software testing institution? First flight software evaluation is an expert
这个高颜值的开源第三方网易云音乐播放器你值得拥有
mysql如何合并数据
supervisor 使用文档
You deserve this high-value open-source third-party Netease cloud music player
树莓派串口登录与SSH登录方法
Multithreading and concurrent programming (2)