我如何在Go中使用(通用)向量?

huangapple go评论91阅读模式
英文:

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 &lt; 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 &quot;container/vector&quot;
import &quot;fmt&quot;

func main() {
     vec := vector.New(0);
     buf := make([]byte,10);
     vec.Push(buf);

     for i := 0; i &lt; vec.Len(); i++ {
     el := vec.At(i).([]byte);
     fmt.Print(el,&quot;\n&quot;);
     }
}

huangapple
  • 本文由 发表于 2009年11月13日 08:14:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/1726336.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定