本文介绍了如何使用(通用)向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Vector类型来存储字节数组(变量大小)

$ p $ store:= vector.New(200 );
...
rbuf:= make([] byte,size);
...
store.Push(rbuf);

这一切都很好,但是当我尝试检索值时,编译器告诉我我需要使用类型断言。所以我把它们加进去,然后尝试一下:

  for i:= 0;我< store.Len(); i ++ {
el:= store.At(i)。([] byte);
...

但是,当我运行它时,它会保留:

 接口是nil,不是[] uint8 
throw:接口转换

任何想法我都可以从Vector的空接口元素'cast'/ convert中转换,这个元素接口用于将其数据存储到我想要使用的实际[]字节数组中随后?






更新(Go1):

解决方案

这适用于我。你初始化了你的矢量的前200个元素吗?如果你不是,他们可能是零,这将是你的错误的来源。

 包主

import vectorcontainer / vector
importfmt

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

for i:= 0;我< vec.Len(); i ++ {
el:= vec.At(i)。([] byte);
fmt.Print(el,\\\
);
}
}


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.

解决方案

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");
     }
}

这篇关于如何使用(通用)向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 08:50