当前位置:网站首页>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)
}
边栏推荐
- 顶测分享:想转行,这些问题一定要考虑清楚!
- 【每日一题】729. 我的日程安排表 I
- C - Inheritance - hidden method
- Librosa audio processing tutorial
- leetcode1020. 飞地的数量(中等)
- Misc of BUU (update from time to time)
- 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
- 微信脑力比拼答题小程序_支持流量主带最新题库文件
- You deserve this high-value open-source third-party Netease cloud music player
- MVVM of WPF
猜你喜欢

LeetCode 78:子集

Due to high network costs, arbitrum Odyssey activities are suspended, and nitro release is imminent

3. Business and load balancing of high architecture

Depth residual network

Cookie Technology & session Technology & ServletContext object

漏了监控:Zabbix对Eureka instance状态监控

19.段页结合的实际内存管理

UWA Pipeline 2.2.1 版本更新说明

树莓派3B更新vim
![[server data recovery] case of offline data recovery of two hard disks of IBM server RAID5](/img/c3/7a147151b7338cf38ffbea24e8bafd.jpg)
[server data recovery] case of offline data recovery of two hard disks of IBM server RAID5
随机推荐
Refer to how customer push e-commerce does content operation
LeetCode Algorithm 2181. Merge nodes between zero
Huawei equipment configuration ospf-bgp linkage
The best way to learn SEO: search engine
【Hot100】739. 每日温度
配置树莓派接入网络
BUU的MISC(不定时更新)
Establishment and operation of cloud platform open source project environment
Is software testing outsourcing going or not? Three years' real outsourcing experience tells you
Misc of BUU (update from time to time)
SSM learning
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
简单描述 MySQL 中,索引,主键,唯一索引,联合索引 的区别,对数据库的性能有什么影响(从读写两方面)
指尖上的 NFT|在 G2 上评价 Ambire,有机会获得限量版收藏品
How are the open source Netease cloud music API projects implemented?
Introduction to ros2 installation and basic knowledge
Uncaught typeerror: cannot red properties of undefined (reading 'beforeeach') solution
3. Business and load balancing of high architecture
JDBC学习笔记
巴比特 | 元宇宙每日必读:中国互联网企业涌入元宇宙的群像:“只有各种求生欲,没有前瞻创新的雄心”...