英文:
How do I use a (generic) vector in go?
问题
我正在使用Vector类型来存储字节数组(可变大小)
store := vector.New(200);
...
rbuf := make([]byte, size);
...
store.Push(rbuf);
这一切都很顺利,但是当我尝试检索值时,编译器告诉我需要使用类型断言。所以我加入了这些,并尝试
for i := 0; i < store.Len(); i++ {
el := store.At(i).([]byte);
...
但是当我运行这个程序时,它会报错:
interface is nil, not []uint8
throw: interface conversion
你有什么办法可以从Vector使用的空Element接口“转换”/转换为我随后想要使用的实际[]byte数组吗?
更新(Go1): vector包已于2011-10-18被移除。
英文:
I am using a Vector type to store arrays of bytes (variable sizes)
store := vector.New(200);
...
rbuf := make([]byte, size);
...
store.Push(rbuf);
That all works well, but when I try to retrieve the values, the compiler tells me I need to use type assertions. So I add those in, and try
for i := 0; i < store.Len(); i++ {
el := store.At(i).([]byte);
...
But when I run this it bails out with:
interface is nil, not []uint8
throw: interface conversion
Any idea how I can 'cast'/convert from the empty Element interface that Vector uses to store its data to the actual []byte array that I then want to use subsequently?
Update (Go1): The vector package has been removed on 2011-10-18.
答案1
得分: 8
这对我来说很好用。你是否初始化了你的向量的前200个元素?如果没有,它们可能是nil,这可能是你错误的来源。
package main
import vector "container/vector"
import "fmt"
func main() {
vec := vector.New(0);
buf := make([]byte,10);
vec.Push(buf);
for i := 0; i < vec.Len(); i++ {
el := vec.At(i).([]byte);
fmt.Print(el,"\n");
}
}
英文:
This works fine for me. Have you initialised the first 200 elements of your vector? If you didn't they will probably be nil, which would be the source of your error.
package main
import vector "container/vector"
import "fmt"
func main() {
vec := vector.New(0);
buf := make([]byte,10);
vec.Push(buf);
for i := 0; i < vec.Len(); i++ {
el := vec.At(i).([]byte);
fmt.Print(el,"\n");
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论