1

I am pretty new to GO. I was trying few examples and one of them was to use cgo to call a C code from GO.

Here is the example I am trying: https://code.google.com/p/go-wiki/wiki/cgo

With the above link as a reference I created a package structure as below:

gocode/src/github.com/mypkg/test.go

"mypkg" is the custom package that I have created and used it in the test.go as below:

package mypkg

I get an error when I run my go program. "go run: cannot run non-main package"

I have set my GOPATH to the GO source code folder.

GOPATH=/xyz/gocode/src/

I searched for solutions and found the below links which says, custom pacakages cannot be created: https://groups.google.com/forum/#!topic/golang-nuts/vmebkoqYMH4

http://stackoverflow.com/questions/23870801/go-run-cannot-run-non-main-package

But, All the code I see is with a custom pacakage name. Please help me to resolve this issue.

Any help is really appreciated.

Thanks

3 Answers3

3

Create dir mypackage and mypackage.go in $GOPATH

put in mypackage.go following code

package mypackage

func Hello() {
   println("hello")
}

Create main.go

package main

import "mypackage"

func main() {
     mypackage.Hello()
}

go run command must be applied to main package

In you case, create main.go file and import github.com/mypkg

Also importing packages should not contain main function.

Zhuharev
  • 197
  • 4
2

go run is for executables, and works on separate files. Use go install and go build to work with packages. Additional reading: http://golang.org/doc/code.html.

Ainar-G
  • 34,563
  • 13
  • 93
  • 119
0

I have been through this problem. It is showing this error because there is no main package in any .go file. You should create a main folder in which create a main.go file to call main package function main and import your package in that just like below:

package main 
import(
    "fmt"
    "github.com/mypkg"
)
func main(){
// use use your package functions here by packagename.functionname
    mypkg.functionName()
    fmt.Println("Hello")
}

Now build the package by moving to mypkg directory and run go build on terminal or command line if you are window user. Move up to main directory which contains main.go file and run go install it will create executable file in the name of main directory. The directory structure be like.

workspace
  ├── bin
  │   └── app
  ├── pkg
  │   └── linux_amd64
  |         └── user
  |              └── handlers.a
  └── src
    ├── bitbucket.org
    ├── github.com
         └── user
              └── app
                   ├── main.go
                   └── mypkg
                         └──mypkg.go
Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81
Himanshu
  • 12,071
  • 7
  • 46
  • 61