<p>How can I get length (int) of byte slice content? I need to read to the last byte, for position != length { }</p>
<p>The slice content length is 202. However, when I use len(data) it returns 4084 which is probably the buffer size, not the size of the buffer content.</p>
<hr/>**评论:**<br/><br/>chickenphobia: <pre><p>Can you rephrase this? Maybe with a stub example showing expected behavior?</p>
<p>As currently worded, sounds like you should use the len() built-in</p>
<pre><code>lastByte := myByteSlice[len(myByteSlice) - 1]
</code></pre></pre>win32re: <pre><p>Well, in this case, the slice content length is 202. However, when I use len(data) it returns 4084 which is probably the buffer size, not the size of the buffer content.</p></pre>davecheney: <pre><p>Are you reslicing the []byte after the call to Read ?</p></pre>win32re: <pre><p>That was the problem, after reslicing it everything works fine. Thanks!</p></pre>mperham: <pre><p>I suspect you are talking about the difference between len() and cap(). <a href="http://golang.org/doc/effective_go.html#slices" rel="nofollow">http://golang.org/doc/effective_go.html#slices</a></p></pre>jerf: <pre><p>The local answer is that <a href="http://play.golang.org/p/q9zgarI6dB" rel="nofollow">len gives the length of a byte slice</a>.</p>
<p>The global answer is that it sounds like you want <a href="http://golang.org/pkg/io/#ReadFull" rel="nofollow"><code>io.ReadFull</code></a>. <code>io.ReadFull</code> nicely collapses the space of possible behaviors to "you got that many bytes", "the stream ended before you got that many bytes", and "the function never returned because it's still waiting for bytes". If this is a network, combine it with timeouts on the socket and you can also essentially remove that third possibility. This all combines to make networking code reasonably pleasant to write.</p></pre>win32re: <pre><p>Fixed. I didn't use the length from conn.Read and my buffer size was set to 4096. Therefore, len(buf) was returning a big buffer size which was correct but due to me not reslicing the buffer it was wrong.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传