0
votes

I am using go version go1.11.2 windows/amd64 in windows 10

i have folder in desktop with name "GoPro" which has one file - main.go one folder - Modules

The "Modules" folder contains one file - Modules.go

Folder Structure

Desktop
   |------->GoPro
               |----->main.go
               |----->Models
                          |---->Models.go

main.go

// desktop/GoPro/main.go 

package main

import (
    "./Models"
)

func main() {
    Models.Printhello()
}

Models.go

// desktop/GoPro/Models

package Models

import "fmt"

func Printhello() {
    fmt.Println("Hello")
}

If try to run the main.go , I am getting the below error , Go recongise the package but it saying undefined.

go run main.go

command-line-arguments

.\main.go:8:2: undefined: Models

The folder is not in GOPATH. I am just trying to import the package with in sub folder of main.go

1
Please read How to Write Go Code. You do not import files but packages and probably your package is not called "Models". Also: Do not use relative imports as this is a stupid idea.Volker
Is there perhaps a duplicate that explains why relative imports are a bad idea?ᆼᆺᆼ
@Volker Why relative imports are stupid idea. In many website I saw , people are saying not to use relative imports. I am just trying to port my codes form Python to Go, In python all my additional packages are imported relative path. To maintain the same structure I am trying to import packages in relative path.Arvindh
Relative imports do not play well along all the tooling. Using full qualified import paths is dead simple and will result in a project structure which works well. Spending 5 minutes to convert to full import paths is much less work than wasting hours fiddling with relative imports. Relative imports turned out to be a stupid idea and using them will result in needless problems. You can still maintain the same file system structure, all you need to do is use non-relative import paths. It really is that simple. And please: Decapitalise the model name!!Volker
@Volker. Thanks. hereafter I will follow the standard waysArvindh

1 Answers

1
votes

You can either set up $GOPATH and place your library in a path relative to $GOPATH, or use modules.

For modules, you can do something like:

$ tree
.
├── go.mod
├── main.go
└── mylib
    └── mylib.go

Contents of files:

$ cat go.mod
module myproject.com

====

$ cat main.go 
package main

import "myproject.com/mylib"

func main() {
    mylib.Say()
}

====

$ cat mylib/mylib.go 
package mylib

import "fmt"

func Say() {
    fmt.Println("Hello from mylib")
}

P.S. use lowercase to name packages/modules