我想使用 Google Cloud Platform Datastore 进行数据分页,我在 GCP 的页面 ( https://cloud.google.com/datastore/docs/concepts/queries ) 上找到了一个使用 Cursors 进行分页的示例,它工作得非常好。
Google 提供的示例对变量 var tasks []Task 和 var task Task 进行了硬编码,我想创建一个可重用函数,我可以在其中通过类型为 interface{} 的参数将指针传递给结构数组,并让该结构由该函数填充。例如:
type MyStruct1 struct {
F1 string
}
type MyStruct2 struct {
F1 int
}
func list(ctx context.Context, cursorStr string, data interface{}) {
...
}
func main() {
mystruct1 := make([]MyStruct1, 0)
list(ctx, "", &mystruct1)
mystruct2 := make([]MyStruct2, 0)
list(ctx, "", &mystruct2)
}
当我需要在此函数中创建一个变量来存储记录,然后将其附加到作为指针传递的结构数组时,我的问题就开始了。
Google 示例
func SnippetIterator_Cursor() {
ctx := context.Background()
client, _ := datastore.NewClient(ctx, "my-proj")
cursorStr := ""
// [START datastore_cursor_paging]
const pageSize = 5
query := datastore.NewQuery("Tasks").Limit(pageSize)
if cursorStr != "" {
cursor, err := datastore.DecodeCursor(cursorStr)
if err != nil {
log.Fatalf("Bad cursor %q: %v", cursorStr, err)
}
query = query.Start(cursor)
}
// Read the tasks.
var tasks []Task << THIS IS WHAT I WANT TO BE GENERIC
var task Task. << THIS IS WHAT I WANT TO BE GENERIC
it := client.Run(ctx, query)
_, err := it.Next(&task)
for err == nil {
tasks = append(tasks, task)
_, err = it.Next(&task)
}
if err != iterator.Done {
log.Fatalf("Failed fetching results: %v", err)
}
// Get the cursor for the next page of results.
nextCursor, err := it.Cursor()
// [END datastore_cursor_paging]
_ = err // Check the error.
_ = nextCursor // Use nextCursor.String as the next page's token.
}
我的基于上面代码的通用函数
func list(ctx context.Context, kind string, data interface{}, pageSize int, cursorStr string) string {
query := datastore.NewQuery(kind).Limit(pageSize)
if cursorStr != "" {
cursor, err := datastore.DecodeCursor(cursorStr)
if err != nil {
log.Fatalf("Bad cursor %q: %v", cursorStr, err)
}
query = query.Start(cursor)
}
it := query.Run(ctx)
// HERE IS WHERE THE PROBLEM STARTS
var vet []interface{}
var rec interface{}
k, err := it.Next(rec)
if err != nil {
log.Println(err.Error())
}
for err == nil {
log.Println(k, rec) // PROBLEM: The key comes ok but rec comes nil
vet = append(vet, rec)
k, err = it.Next(rec)
}
log.Println(vet) // PROBLEM: vet has only nils
nextCursor, err := it.Cursor()
if err != nil {
log.Println(err.Error())
}
data = vet
return nextCursor.String()
}
func TestListFunc() {
data := make([]Tasks, 0)
cursor := list(ctx, "Tasks", &data, 10, "")
x, _ := json.MarshalIndent(data, " ", " ")
log.Println(string(x))
}
问题:数据存储迭代器 .Next() 似乎没有将记录存储在类型为 interface{} 的变量中p>
最佳答案
使用 reflect包裹:
func list(ctx context.Context, kind string, dst interface{}, pageSize int, cursorStr string) string {
client, _ := datastore.NewClient(ctx, "my-proj")
query := datastore.NewQuery(kind).Limit(pageSize)
if cursorStr != "" {
cursor, err := datastore.DecodeCursor(cursorStr)
if err != nil {
log.Fatalf("Bad cursor %q: %v", cursorStr, err)
}
query = query.Start(cursor)
}
// Get reflect value for the result slice.
results := reflect.ValueOf(dst).Elem()
// Allocate new value of the slice element type.
// resultp is pointer to that value.
resultp := reflect.New(results.Type().Elem())
it := client.Run(ctx, query)
_, err := it.Next(resultp.Interface())
for err == nil {
// Append last value to results
results.Set(reflect.Append(results, resultp.Elem())
_, err = it.Next(resultp.Interface())
}
if err != iterator.Done {
log.Fatalf("Failed fetching results: %v", err)
}
// Get the cursor for the next page of results.
nextCursor, err := it.Cursor()
// [END datastore_cursor_paging]
_ = err // Check the error.
_ = nextCursor // Use nextCursor.String as the next page's token.
}
使用指向目标 slice 的指针调用函数:
var data []Tasks
cursor := list(ctx, "Tasks", &data, 10, "")
关于go - 填充作为指针传递给函数的结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53254726/
我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h
我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby数组,我们在StackOverflow上找到一
我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]
我正在使用puppet为ruby程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这
我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere
这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife
我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re
我有一个这样的哈希数组:[{:foo=>2,:date=>Sat,01Sep2014},{:foo2=>2,:date=>Sat,02Sep2014},{:foo3=>3,:date=>Sat,01Sep2014},{:foo4=>4,:date=>Sat,03Sep2014},{:foo5=>5,:date=>Sat,02Sep2014}]如果:date相同,我想合并哈希值。我对上面数组的期望是:[{:foo=>2,:foo3=>3,:date=>Sat,01Sep2014},{:foo2=>2,:foo5=>5:date=>Sat,02Sep2014},{:foo4=>4,:dat