Search code examples
goimportmodulepackagelocal

How to import a .go file in the "include" sense from relative local folder


I am trying to include a ".go" file which contains some struct declarations which I will need in different standalone projects

Currently the error is as follows:

main.go:8:2: module include@latest found (v0.0.0, replaced by ./include), but does not contain package include/declare

Tree structure:

/home/dev/go/sample
            include/  
            main.go  
            go.mod

/home/dev/go/sample/include
            declare.go
            go.mod

Content of the /home/dev/sample/go.mod:

go 1.14
module include
replace include v0.0.0 => ./include

Content of the /home/dev/sample/include/go.mod:

module include
go 1.14
require include v0.0.0
replace include v0.0.0 => include

Import from "main.go":

package main
import (
      "encoding/json"
      "fmt"
      "io/ioutil"
      "os"
      "include/declare"
)

Thank's


Solution

  • Following the assiduous reading proposed by @enzo, my request is now functional

    Sample structure:

    ├── go.mod
    ├── include
    │   ├── sourceA.go
    │   └── sourceB.go
    └── myapp.go
    

    The solution is to create a simple correct "go.mod" file at the main application level. No need, in my case, to have one in the "include" folder

    go mod init <name of your app>
    

    Contents of the go.mod file:

    MyApp module
    go 1.14
    

    Content of include/sourceA.go :

    package include
    
    const ValueA = "a value from sourceA.go"
    
    func FunctionA () {
        println("Hello: sourceA.go")
    }
    

    Content of include/sourceB.go :

    package include
    
    const ValueB = "a value from sourceB.go"
    
    func FunctionB () {
        println("Hello: sourceB.go")
    }
    

    Content of myapp.go :

    package main
    
    import "myapp/include"
    
    func main() {
        include.FunctionA()
        include.FunctionB()
        println(include.ValueA)
        println(include.ValueB)
    }
    

    The import management (everything is module/packages) is not necessarily obvious to understand at the start of the apprentices in Go, but once "understood", it is since more logical, especially for an "include" approach than have found it in other languages.

    Hope this will be useful to others for a better code file organization (there are certainly better methods, but this one meets my needs, for the moment)