<p>Hi folks. I have an <code>ID uint</code> on a model. I need to add to a RabbitMQ stack which only takes a slice of bytes, and I want to pass this ID as a slice of bytes. On my next service I want to grab this slice of bytes, convert it to a string (or back to uint would even be OK), and do a lookup based on it. I am fairly new to typed languages, and this is my first real roadblock so far. </p>
<p>I tried this: </p>
<pre><code>func UIntToByteSlice(num uint) []byte {
b := make([]byte, 8)
binary.LittleEndian.PutUint64(b, uint64(num))
return b
}
</code></pre>
<p>but when I pull the <code>string(ID)</code> on my other service, <code>ID</code> being the slice of bytes, I just get a unicode box with "0 0 0 2" in it. I am definitely pulling the byte slice off the stacks, I just can't get the hang of conversion, and tbh, this is my first real foray into "LittleEndian" and stuff like this. Can anyone assist or point me in the right direction please? : )</p>
<hr/>**评论:**<br/><br/>RenThraysk: <pre><p>The receiving end has to read the value using binary.LittleEndian.Uint64()</p></pre>diabetesjones: <pre><p>Thank you very much!! This works, but I started reading more about conversion, and it seems simpler to do this if I want the end result as a string (which would be better)</p>
<pre><code> // UIntToByteSlice is a helper function to convert down to byte slices to add to the
// RabbitMQ stack
func UIntToByteSlice(num uint) []byte {
str := strconv.Itoa(int(num))
return []byte(str)
}
</code></pre>
<p>And now on my receiving end I just grab the ID and do <code>string(ID)</code>.</p></pre>epiris: <pre><p>I would put the message in a struct and use json, or use the binary package if performance is a concern. Well formed standard encoding scheme is “simpler” in my opinion.</p></pre>diabetesjones: <pre><p>That does sound better as it enforces a standard on both ends. Will do that monday!</p></pre>gergo254: <pre><p>Or he can even try protobuf. :)</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传