R
R
Roman Rakzin2015-07-15 00:18:29
go
Roman Rakzin, 2015-07-15 00:18:29

How to include another file in golang?

Tell me, maybe a banal question, how to connect another file in golang?
I just started experimenting with it and so far I am writing in one file.
I would like to transfer part of the code to another and connect it to main.go

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Artem, 2015-07-15
@TwoRS

For beginners, there are two articles that are required reading. The first is " How to Write Go Code " and the second is " Understanding Golang Packages "
In short, Go doesn't include a file, but imports a module (package of files).
main.go:

package main

import "./mymodule"

func main() {
    mymodule.MethodOne()
}

mymodule/some_file.go:
package mymodule

import "fmt"

func MethodOne() {
    fmt.Println("Hello World!")
}

But this is an example of a relative import, without regard to the $GOPATH environment variable. For more details, see the links above.

L
Lesha Kiselev, 2015-07-15
@Yakud

Please tell me, did you search for the answer to this question in Google?
https://golang.org/doc/code.html

N
Nikita Prystupchik, 2018-05-19
@zlbrk

Suppose we have a hello.go file with the following content

package main

import "fmt"

const(
 constString="Hello, constant!"
)

func main() {
    fmt.Println(constString)
}

will result in
I just want to move all the constant definitions to another file, staying within the same package, without having to practice importing packages and exporting names.
In the same directory I create a file myConst.go with the following content
package main // Это важно!

const(
 constString="Hello, constant!"
)

In the hello.go file, I delete the line with the declaration of the constant
package main

import "fmt"

func main() {
    fmt.Println(constString)
}

If everything is done correctly, then the output will be the same as in the original example.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question