Search code examples
gojupyter-notebookprogram-entry-point

Having trouble getting started on go. `package main` throws run time error- index out of range?


I'm a complete beginner in go. And I just installed gophernotes and intend to use Jupyter Notebook for main programming.

This program gives the following error when run in Jupyter:

Cell1: package main
Out1: runtime error: index out of range
Cell2: import "fmt"
      func main() {
          fmt.Println("hello world")
      }
      main()
Out2: hello world

When I write the same in a test.go and execute from bash: go run test.go, I get the following:

Deepaks-MacBook-Air:JUPYTER deepak$ go run test.go 
go: disabling cache (/Users/deepak/Library/Caches/go-build) due to initialization failure: open /Users/deepak/Library/Caches/go-build/log.txt: permission denied
# command-line-arguments
./test.go:6:1: syntax error: non-declaration statement outside function body

Solution

  • I think that having "package main" is a problem. The way Go works with Jupyter is apparently different than how Go works on its own. You don't need a package statement with Jupyter.

    Also you should never call main(). That is done automatically when you run the program with go run or go build.

    I am not familiar with Jupyter Notebook and how it uses Go. Maybe you do need to call the function. If that is the case do not name your function main because that is simply confusing.

    From what I have seen of Jupyter / Go examples you don't need a Go function you can just list out the code.