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

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

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.

package main

import "fmt"
import "strconv"

func writeHello(i int, ) {
    	fmt.Printf("hello, world "+strconv.Itoa(i)+"\n")
}

type SliceStruct struct {
    data [][]int;
}

func (s SliceStruct) New() {
    s.data=make([][]int,10);
}

func (s SliceStruct) AllocateSlice(i int) {
    s.data[i]=make([]int,10);
}

func (s SliceStruct) setData(i int, j int, data int) {
    s.data[i][j] = data;
}

func (s SliceStruct) getData(i int, j int) int {
    return s.data[i][j]
}

func useSliceStruct(){
    sliceStruct := SliceStruct{};
    sliceStruct.New();
    for i := 0; i < 10; i++ {
	    sliceStruct.AllocateSlice(i);
	    for j:=0; j<10; j++ {
		     sliceStruct.setData(i,j,i);
		    writeHello(sliceStruct.getData(i,j));
	    }
    }
}

func dontUseSliceStruct(){
    data:=make([][]int,10);
    for i := 0; i < 10; i++ {
	    data[i]=make([]int,10);
	    for j:=0; j<10; j++ {
		    data[i][j] = i;
		    writeHello(data[i][j]);
	    }
    }
}

func main() {
    dontUseSliceStruct();
    useSliceStruct();
}

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,刚刚解决了。

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

func (s SliceStruct)

应该是

func (s *SliceStruct)
英文:

DOH, just worked it out.

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

func (s SliceStruct)

Should have been

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:

确定