当前位置:网站首页>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)
}
边栏推荐
- Path analysis model
- TS基础篇
- What does UDP attack mean? UDP attack prevention measures
- Solution to the problem of breakthrough in OWASP juice shop shooting range
- 数据仓库建设思维导图
- Yield method of tread
- 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
- leetcode1020. Number of enclaves (medium)
- The differences and advantages and disadvantages between cookies, seeion and token
- 【Hot100】739. Daily temperature
猜你喜欢
leetcode1020. 飞地的数量(中等)
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
leetcode35. 搜索插入位置(简单,找插入位置,不同写法)
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
leetcode704. Binary search (find an element, simple, different writing)
Cif10 actual combat (resnet18)
Fast target recognition based on pytorch and fast RCNN
Prefix and array series
hydra常用命令
After sharing the clone remote project, NPM install reports an error - CB () never called! This is an error with npm itself.
随机推荐
win10 64位装三菱PLC软件出现oleaut32.dll拒绝访问
Cookie Technology & session Technology & ServletContext object
Fast target recognition based on pytorch and fast RCNN
18. Multi level page table and fast table
Compile, connect -- notes-2
OpenGL ES 学习初识(1)
首发织梦百度推送插件全自动收录优化seo收录模块
Applied stochastic process 01: basic concepts of stochastic process
JDBC学习笔记
Wechat official account infinite callback authorization system source code, launched in the whole network
SEO学习的最好方式:搜索引擎
WPF之MVVM
supervisor 使用文档
C language_ Double create, pre insert, post insert, traverse, delete
Kubernetes cluster builds ZABBIX monitoring platform
Misc of BUU (update from time to time)
接口自动化测试框架:Pytest+Allure+Excel
GET 和 POST 请求类型的区别
Résumé de la structure du modèle synthétisable
Is software testing outsourcing going or not? Three years' real outsourcing experience tells you