GoLang:在函数中分配切片的切片会导致索引超出范围的错误。

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

GoLang: Allocating Slice of Slices in functions results in index out of range

问题

我一直在尝试一些Go语言的东西,但遇到了一个无法解决的问题。

当代码执行到useSliceStruct函数时,第一次调用AllocateSlice()时会出现索引超出范围的错误。

据我所知,这两个方法的代码是相同的。那么我错过了什么?

英文:

I've been trying some things out in Go and I've hit a problem that I can't figure out.

  1. package main
  2. import "fmt"
  3. import "strconv"
  4. func writeHello(i int, ) {
  5. fmt.Printf("hello, world "+strconv.Itoa(i)+"\n")
  6. }
  7. type SliceStruct struct {
  8. data [][]int;
  9. }
  10. func (s SliceStruct) New() {
  11. s.data=make([][]int,10);
  12. }
  13. func (s SliceStruct) AllocateSlice(i int) {
  14. s.data[i]=make([]int,10);
  15. }
  16. func (s SliceStruct) setData(i int, j int, data int) {
  17. s.data[i][j] = data;
  18. }
  19. func (s SliceStruct) getData(i int, j int) int {
  20. return s.data[i][j]
  21. }
  22. func useSliceStruct(){
  23. sliceStruct := SliceStruct{};
  24. sliceStruct.New();
  25. for i := 0; i < 10; i++ {
  26. sliceStruct.AllocateSlice(i);
  27. for j:=0; j<10; j++ {
  28. sliceStruct.setData(i,j,i);
  29. writeHello(sliceStruct.getData(i,j));
  30. }
  31. }
  32. }
  33. func dontUseSliceStruct(){
  34. data:=make([][]int,10);
  35. for i := 0; i < 10; i++ {
  36. data[i]=make([]int,10);
  37. for j:=0; j<10; j++ {
  38. data[i][j] = i;
  39. writeHello(data[i][j]);
  40. }
  41. }
  42. }
  43. func main() {
  44. dontUseSliceStruct();
  45. useSliceStruct();
  46. }

When it gets to the function useSliceStruct, the code fails at the first call to AllocateSlice() with an index out of range error.

As far as I can tell the code for the two methods does idential things. So what am I missing?

答案1

得分: 1

DOH,刚刚解决了。

在函数声明中,我没有使用结构体的引用。

  1. func (s SliceStruct)

应该是

  1. func (s *SliceStruct)
英文:

DOH, just worked it out.

I wasn't using a reference to the struct in the function declarations.

  1. func (s SliceStruct)

Should have been

  1. func (s *SliceStruct)

huangapple
  • 本文由 发表于 2013年9月28日 02:16:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/19057495.html
匿名

发表评论

匿名网友

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

确定