SQL Valuer/Scanner Interface Issue

xuanbao · · 1066 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I am trying to automate the saving/loading of custom structs with a sqlite database (database/sql) but I am having issues converting a gocql.UUID field (github.com/gocql/gocql). </p> <p>Value() works fine, converting the gocql.UUID into a string, but Scan() isn&#39;t able to cast the value to a string.</p> <pre><code>type Uid struct { gocql.UUID } func (u *Uid) Scan(value interface{}) error { ... if sv, err := driver.String.ConvertValue(value); err == nil { if v, ok := sv.(string); ok { // &lt;--- THIS DOESN&#39;T WORK parsedUUID, _ := gocql.ParseUUID(v) ... } } } </code></pre> <p>Any suggestions would be appreciated!</p> <p>Full code here, issue on line 66: <a href="https://play.golang.org/p/ndCZTJZ5rb" rel="nofollow">https://play.golang.org/p/ndCZTJZ5rb</a></p> <p>edit: added package names, added short example</p> <hr/>**评论:**<br/><br/>65a: <pre><p>&#34; If the value is already a string or []byte, it&#39;s unchanged. &#34; </p> <p>Have you tried assuming it is []byte?</p></pre>EbonyFalcon: <pre><p>fmt.Sprintf(&#34;%s&#34;, sv&#34;) ended up doing it... :|</p> <p>Thanks for the insight!</p></pre>65a: <pre><p>You should be able to type assert it to []byte and then string() cast it, it will be faster than fmt.Sprintf.<br/> <a href="https://play.golang.org/p/zFEUxwmvW4" rel="nofollow">https://play.golang.org/p/zFEUxwmvW4</a></p></pre>EbonyFalcon: <pre><p>Awesome, thanks!</p></pre>lausan: <pre><p>Use the FromBytes function</p> <p>Edit: gocql.FromBytes won&#39;t work if you&#39;re storing the uuid as its string representation. But you could store it as binary to save some storage space</p></pre>dchapes: <pre><p><del>What <code>FromBytes</code> function are you referring to? I find no such function anywhere in Go 1.9&#39;s std packages.</del> [Thanks for the clarification, I had missed the <code>gocql</code> reference and even I had seen it wasn&#39;t aware of if it having that function.]</p></pre>lausan: <pre><p>Edited for clarity and it sounds like FromBytes wouldn&#39;t work with how the uuids are being stored</p></pre>oscooter: <pre><p>Is your code good2go now?</p></pre>EbonyFalcon: <pre><p>Yep!</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1066 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传