Break project into subfolders

I want to split my project into subfolders.

I want this code structure:

├── main.go
└── models
    └── user.go

Where main.go is located:

package main

import (
  "fmt"
  "./models"
)

func main(){
  fmt.Println(User{"new_user"})

}

And user.go is:

package models

type User struct {
  Login string
}

But the user is not defined in the main package, and the warning about import increase is "imported and not used."

What am I doing wrong? My project is simple (not such an example, but with only a few files (controllers and models)), and I want a simple structure.

Maybe I'm doing this completely wrong?

The problematic project is here: https://github.com/abonec/go_import_problem

+14
source share
6 answers

I recently achieved this using go modules .

Golang opt-in v1.11.1, , , $GOPATH. , , ~/development, . , go : GO111MODULE=on.

Go v1.11.3 2019 .


( ).

~/Dev/my-app
 ├── src/
 │   ├── one/
 │   │   ├── two/
 │   │   │   └── two.go
 │   │   └── one.go
 │   └── zero.go
 ├── go.mod
 └── app.go

my-app, app.go go.mod go , .

, two.go, , Two, app.go my-app/src/one/two.

, :

go.mod

module my-app

two.go

package two

func Two() string {
    return "I'm totally not supposed to be using go modules for this"
}

app.go

package main

import "my-app/src/one/two"

func main() {
    two.Two()
}

two.TheNewFunc() /, two.TheNewFunc() TheNewFunc() .

GitHub , .

+8

:

import "github.com/abonec/go_import_problem/models"

, :

import "go_import_problem/models"

( : "the name of your project folder accessible by GOPATH/your package" )

. " golang?".

:

models.User

:

, , .
( . , , , .)


kostix :

, Go ( , ./, ../, - ), , "" , $GOPATH.

Go , , .
. , URL- - , .

+6

So

fmt.Println(models.User{"new_user"})
0

go, , .

, , , . , API-.

0

"go/src"

└── go
    └── src
        └── myAwesomeProject
            ├── main.go
            └── models
                └── user.go

main.go

package main

import (
  "fmt"
  "myAwesomeProject/models"
)

, , .

0

. ,

import "./models"

with structure User must use it as

models.User
-5
source

Source: https://habr.com/ru/post/1537094/


All Articles