Import/insert other files - go (golang)

Asked

Viewed 921 times

0

I am studying go (golang) and I have a question regarding the import of files, the doubt is about something "elementary" but I could not find anything specifically about it.

I have a package (test) so arranged:

test -> main.go
     -> test.go

I would like to import the test go. inside main go.?

//em javascript seria algo assim:
//main.go
require('./test.go')

How to do the same in go?

2 answers

1

Golang uses a package system, so there’s no way you can import "a single file".

I don’t know what your situation is there exactly, but if both files belong to the same package, then there is no need to import anything, it is as if they are a single large file. If they are in separate packages, you can import the package.

import "meupacote"

or

import (
    "umpacote"
    "outropacote"
)

Remembering that the import declaration should come right after the name of your package.

package main

import "fmt"

func main() {
    fmt.Printf("Hello, world.\n")
}

Once imported, all exported identifiers (first uppercase letter) of the package are available to use.

I recommend using the word test carefully, after all, it has special significance during the compilation and execution of tests.

  • On youtube you have plenty of material explaining about packages. https://www.youtube.com/watch?v=n9hPwNx_UPI

0

as it ta inside the main directory, it is not necessary to matter, in this case just call the functions and variables that are inside the test.go file

if your file was between or package as for example:

-> main -> main.go -> example/-> example.go

in this case you would have to import in your main.go file:

package main
import "principal/exemplo"
import "fmt"

func main(){
   fmt.Println(exemplo("Olá, Exemplo!"))
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.