Question

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.

Was it helpful?

Solution

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");
     }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top