Im new in GoLang and im looking for some help. Im working with Windows 10 and Visual Studio Code.
What i want to do is to use Enums
in my main.go
file. I make a folder for it named "Enums", and file in it named SQLQuerys.go
that looks like this:
package SqlQuerys
type SqlQuery string
const (
CreateTable SqlQuery = `CREATE TABELE key.users(id int, email text, title text, content text, magic_number int, PRIMARY KEY(id));`
)
So it is simple string that i want to pass in function in main.go
that looks like this (i commented query that works fine):
package main
import (
"log"
SqlQuerys "golangapi/Enums" //import enums here
"github.com/gocql/gocql"
)
func main() {
// connect to the cluster
cluster := gocql.NewCluster("127.0.0.1")
cluster.ProtoVersion = 3
cluster.Keyspace = "key"
cluster.Consistency = gocql.Quorum
session, _ := cluster.CreateSession()
defer session.Close()
//if err := session.Query(`CREATE TABEL IF NOT EXISTS key.users(id int, email text, title text, content text, magic_number int, PRIMARY KEY(id));`).Exec(); err != nil {
// log.Fatal(err)
//}
if err := session.Query(SqlQuerys.CreateTable).Exec(); err != nil {
log.Fatal(err)
}
}
How to import one GoLang file to another?
After debug, i get this error:
main.go:6:2: cannot find package "golangapi/Enums" in any of:
C:\Go\src\golangapi\Enums (from $GOROOT)
C:\Users\Admin\go\src\golangapi\Enums (from $GOPATH)
exit status 1
How to make possible to see another .go file in another? Thanks for any advices
Go is more like idiomatic Java. While in Java technically you can mix and match the namespace declarations in files with the directory structure, generally they need to match. In Go, they must match in order to work correctly. Your import path (used in an import
statement) must match either a repo the library can be checked out from, or the path on disk starting from $GOPATH/src
(which should generally be one and the same). The package name (used in the package
statement) should match the last part of the path (the name of the directory containing the file). There is no referencing from one file to another file, only from one file to a package (just like Java). So, to take your example:
$GOPATH
- src/
- golangapi/
- main.go
- enums/
- sqlqueries.go
main.go:
package main
import (
"log"
"golangapi/enums"
"github.com/gocql/gocql"
)
...
if err := session.Query(enums.CreateTable).Exec(); err != nil {
log.Fatal(err)
}
sqlqueries.go:
package enums
type SqlQuery string
const (
CreateTable SqlQuery = `CREATE TABELE key.users(id int, email text, title text, content text, magic_number int, PRIMARY KEY(id));`
)