Can a Go program have multiple packages?

Yes, a Go program can have multiple packages. In Go, packages are used to organize and encapsulate code. Each package can contain its own functions, types, and variables, and you can import these packages into other Go files to use their functionality.

To create a Go program with multiple packages, you typically:

  1. Create a directory for each package.
  2. Define a Go file in each directory with the package keyword at the top.
  3. Use the import statement in your main package to include the other packages.

Here's a simple example:

Directory Structure:

/myproject
    /mypackage
        mypackage.go
    main.go

mypackage/mypackage.go:

package mypackage

import "fmt"

func Hello() {
    fmt.Println("Hello from mypackage!")
}

main.go:

package main

import (
    "myproject/mypackage"
)

func main() {
    mypackage.Hello()
}

In this example, the main package imports mypackage and calls the Hello function defined in it.

0 Comments

no data
Be the first to share your comment!