Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a (generic) vector in go?

Tags:

go

vector

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.

like image 565
Oliver Mason Avatar asked Nov 13 '09 00:11

Oliver Mason


1 Answers

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");
     }
}
like image 187
Scott Wales Avatar answered Nov 13 '22 12:11

Scott Wales