Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

获取xmap中所有数据 怎么获取 #4

Open
erdong01 opened this issue Mar 2, 2022 · 4 comments
Open

获取xmap中所有数据 怎么获取 #4

erdong01 opened this issue Mar 2, 2022 · 4 comments

Comments

@erdong01
Copy link

erdong01 commented Mar 2, 2022

No description provided.

@houseme
Copy link
Contributor

houseme commented Mar 2, 2022

参考:

https://github.com/heiyeluren/xds/blob/177aea6e371a0525bdaf2616832f25075ec153ee/xmap/xmap.go#L89

@erdong01
Copy link
Author

erdong01 commented Mar 2, 2022

Get(key interface{}) 是获取单条数据吧 我不是很理解怎么用可以获取全部

@heiyeluren
Copy link
Owner

heiyeluren commented Mar 4, 2022

可以获取,调用Each()接口,可以访问全部的元素:

package main

import (
	"fmt"
	"github.com/heiyeluren/xmm"
	"github.com/heiyeluren/xds"
	"github.com/heiyeluren/xds/xmap"
)

//------------------
// xmap快速使用案例
//------------------

func main() {

	//创建XMM内存块
	f := &xmm.Factory{}
	mm, err := f.CreateMemory(0.75)
	if err != nil {
		panic("error")
	}

	//用xmap创建一个map,结构类似于 map[string]uint,操作类似于 m: = make(map[string]uint)
	m, err := xmap.NewMap(mm, xds.String, xds.Int)
	if err != nil {
		panic("error")
	}
	// 调用Set()给xmap写入数据
	err = m.Set("k1", 1)
	err = m.Set("k2", 2)
	err = m.Set("k3", 3)
	err = m.Set("k4", 4)
	err = m.Set("k5", 5)

	// 调用Get()读取单个数据
	ret, exists, err := m.Get("k1")
	if exists == false {
		panic("key not found")
	}
	fmt.Printf("Get data key:[%s] value:[%s] \n", "k1", ret)

	// 使用Each()访问所有xmap元素
	// 在遍历操作中,让全局变量可以在匿名函数中访问(如果需要使用外部变量,可以像这样)
	gi := 1
	//调用 Each 遍历函数
	m.Each(func(key, val interface{}) error {
		//针对每个KV进行操作,比如打印出来
		fmt.Printf("For each XMap all key:[%s] value:[%s] \n", key, val)

		//外部变量使用操作
		gi++
		return nil
	})
	fmt.Printf("For each success, var[gi], val[%s]\n", gi);

	//使用Len()获取xmap元素总数量
	len := m.Len()
	fmt.Printf("Xmap item size:[%s]\n", len);

}

@heiyeluren
Copy link
Owner

具体也可以访问这个测试代码,中间有 Each() 使用案例:
https://github.com/heiyeluren/xds/blob/main/example/xmap_test1.go

调用以后效果大概如这个图:
执行结果图

@erdong01 erdong01 closed this as completed Mar 4, 2022
@heiyeluren heiyeluren reopened this Mar 4, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants