Notification texts go here Contact Us Buy Now!

How to import code from adjacent file in Golang

```html

Importing Code from Adjacent File in Go

In Go, a program is defined by a single un- imported main package. You can't have multiple main packages in a program, so if you want to make a library, e.g. your foo dir, you need to define a different package name.

Imports are handled in Go as follows: 1. They are taken relative to $GOPATH. 2. You can't import a package relative to a specific file.

Example:

Consider the following code:
hello.go:

package main

import . "huru/foo"

func main() {
    SayHi()
}
foo/side.go:

package foo

import "fmt"

func SayHi() {
    fmt.Println("Hello from side.go");
}
In this example, the hello.go program imports the huru/foo package and calls the SayHi() function, which is defined in the foo/side.go file. This code will work fine as long as the package names are different. In this case, main and foo are different package names.

Additional Points:

* You can't use main as the package name of huru/foo/side.go, because it's already used in the huru/hello.go. * It's better to use the folder name as the package name.

```

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.