0

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 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.