当前位置:网站首页>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)
}
边栏推荐
- Uni app practical project
- Zhongqing reading news
- 开源的网易云音乐API项目都是怎么实现的?
- 巴比特 | 元宇宙每日必读:中国互联网企业涌入元宇宙的群像:“只有各种求生欲,没有前瞻创新的雄心”...
- [hot100] 739. Température quotidienne
- 软件测试外包到底要不要去?三年真实外包感受告诉你
- leetcode704. Binary search (find an element, simple, different writing)
- 配置树莓派接入网络
- Prefix and array series
- Development of entity developer database application
猜你喜欢
MVVM of WPF
Configure raspberry pie access network
leetcode704. 二分查找(查找某个元素,简单,不同写法)
Hydra common commands
Oracle database 11gr2 uses TDE transparent data encryption to report an error ora28353. If you run to close the wallet, you will report an error ora28365. If you run to open the wallet, you will repor
How are the open source Netease cloud music API projects implemented?
顶测分享:想转行,这些问题一定要考虑清楚!
Depth residual network
漏了监控:Zabbix对Eureka instance状态监控
leetcode1020. 飞地的数量(中等)
随机推荐
Arduino tutorial - Simon games
[hot100] 739. Température quotidienne
配置树莓派接入网络
What is the biggest problem that fresh e-commerce is difficult to do now
You deserve this high-value open-source third-party Netease cloud music player
Solution to the problem of breakthrough in OWASP juice shop shooting range
Cookie Technology & session Technology & ServletContext object
Establishment and operation of cloud platform open source project environment
leetcode35. 搜索插入位置(简单,找插入位置,不同写法)
将ue4程序嵌入qt界面显示
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
UWA pipeline version 2.2.1 update instructions
Development of entity developer database application
网络安全基础介绍
TS Basics
leetcode841. Keys and rooms (medium)
How to configure GUI guide development environment
Introduction to ros2 installation and basic knowledge
The difference between get and post request types
leetcode1020. 飞地的数量(中等)