-1

This is the directory structure for my Go project:

   my_project
   |
   main.go
   - my_package
       |
       - my_package.go

On main.go this works ok:

import ( "my_package/my_package" )

But when I create a new folder "examples" to test some new functionalities of the package, tha main.go cannot import the package as expected:

   my_project
   |
   main.go
   - my_package
       |
       - my_package.go
   - examples
       |
       - main.go

importing package from parent directory:

import ( "../my_package/my_package" )

Trying running examples/main.go does not work:

cd examples
go run main.go
    build _/mypath/my_project/my_package: cannot find module for path _/mypath/my_project/my_package

Shouldn't I import local packages from parent directories?

Is it always compulsory to have the package modules on subfolders of main.go?

Is there any simple and clear way to organize main/test/debug go programs w/ shared dependencies on local packages?

I've read on golang modules and local packages that maybe I should use abosulte paths for importing packages, but I don't like that option because this is a code meant to be uloaded to a repository, so absolute paths wouldn't work on other implementations.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • 3
    Have you read the official [Tutorial: Get started with Go](https://golang.org/doc/tutorial/getting-started)? If you have more packages, you have to create a `go.mod` file (e.g. `go mod init`). – icza Oct 06 '20 at 10:34
  • 3
    [The language is called Go](https://www.reddit.com/r/golang/comments/30wsrs/the_name_of_our_language_is_go/) – Jonathan Hall Oct 06 '20 at 10:35
  • 1
    And if you just have a single module, you can import any package from it without having to touch `go.mod`. And if you have multiple modules and you want to "stay on disk", see [How to use a module that is outside of “GOPATH” in another module?](https://stackoverflow.com/questions/52328952/how-to-use-a-module-that-is-outside-of-gopath-in-another-module/52330233#52330233) – icza Oct 06 '20 at 10:36
  • Thx! it works! "Replace" in go.mod does the magic – Juan Ignacio Pérez Sacristán Oct 06 '20 at 10:59

1 Answers1

-1

The way to proceed according to stackoverflow masters (and it works perfectly well indeed) is to import a fake repository and then replace it with a local redirection as stated on How to use a module that is outside of "GOPATH" in another module?

In main.go:

import (
        my_package "my_fake_repository/myself/my_project/my_package"
)

In go.mod:

require my_fake_repository/myself/my_project/my_package v0.0.0
replace my_fake_repository/myself/my_project/my_package => ../my_package

It works! Thx a lot!