douqiang5809 2019-03-23 05:34
浏览 69
已采纳

如何写向量

I am using the Go flatbuffers interface for the first time. I find the instructions sparse.

I would like to write a vector of uint64s into a table. Ideally, I would like to store numbers directly in a vector without knowing how many there are up front (I'm reading them from sql.Rows iterator). I see the generated code for the table has functions:

func DatasetGridAddDates(builder *flatbuffers.Builder, dates flatbuffers.UOffsetT) {
    builder.PrependUOffsetTSlot(2, flatbuffers.UOffsetT(dates), 0)
}
func DatasetGridStartDatesVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT {
    return builder.StartVector(8, numElems, 8)
}

Can I first write the vector using (??), then use DatasetGridAddDates to record the resulting vector in the containing "DatasetGrid" table?

  • 写回答

1条回答 默认 最新

  • dongpu2727 2019-03-23 08:16
    关注

    (caveat: I have not heard of FlatBuffers prior to reading your question)

    If you do know the length in advance, storing a vector is done as explained in the tutorial:

    name := builder.CreateString("hello")
    
    q55310927.DatasetGridStartDatesVector(builder, len(myDates))
    for i := len(myDates) - 1; i >= 0; i-- {
        builder.PrependUint64(myDates[i])
    }
    dates := builder.EndVector(len(myDates))
    
    q55310927.DatasetGridStart(builder)
    q55310927.DatasetGridAddName(builder, name)
    q55310927.DatasetGridAddDates(builder, dates)
    grid := q55310927.DatasetGridEnd(builder)
    builder.Finish(grid)
    

    Now what if you don’t have len(myDates)? On a toy example I get exactly the same output if I replace StartDatesVector(builder, len(myDates)) with StartDatesVector(builder, 0). Looking at the source code, it seems like the numElems may be necessary for alignment and for growing the buffer. I imagine alignment might be moot when you’re dealing with uint64, and growing seems to happen automatically on PrependUint64, too.

    So, try doing it without numElems:

    q55310927.DatasetGridStartDatesVector(builder, 0)
    var n int
    for rows.Next() { // use ORDER BY to make them go in reverse order
        var date uint64
        if err := rows.Scan(&date); err != nil {
            // ...
        }
        builder.PrependUint64(date)
        n++
    }
    dates := builder.EndVector(n)
    

    and see if it works on your data.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch