tags:

views:

296

answers:

1

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?

+3  A: 

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");
     }
}
Scott Wales
Yes, thanks! That did it. I assumed the argument was a Java-style capacity 'hint', rather than a fixed pre-set... But I generally find the go documentation rather terse. And the error messages are not very helpful most of the time either!
Oliver Mason
No worries. Remember you can always check the source of go modules in $GOROOT/src/pkg if you're unsure of what's happening
Scott Wales