Go Packages
In Go, packages are used to organize related code into separate namespaces and to promote code reuse. A package is a collection of Go source files in the same directory that are compiled together as a single unit.
To create a package in Go, you typically start by creating a new directory for your package and adding one or more Go source files to it. Each source file in the package should have a package declaration at the top of the file, which specifies the name of the package. For example, a simple package called "myutils" might look like this:
myutils/ ├── math.go └── string.go
math.go:
package myutils func Add(x, y int) int { return x + y } func Subtract(x, y int) int { return x - y }
string.go:
package myutils func Reverse(s string) string { runes := []rune(s) for i, j := 0, len(runes)-1; i < len(runes)/2; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } return string(runes) }
In this example, the myutils
package contains two source files, math.go
and string.go
, which both declare the myutils
package using the package
keyword. The math.go
file contains two functions for adding and subtracting integers, while the string.go
file contains a function for reversing a string.
Once you've created a package, you can use it in other Go programs by importing it with the import
keyword. For example, to use the myutils
package in a program, you would write:
package main import ( "fmt" "myutils" ) func main() { x := 3 y := 4 fmt.Println(myutils.Add(x, y)) // prints "7" fmt.Println(myutils.Reverse("hello")) // prints "olleh" }
In this example, the main
function imports the myutils
package with the import
keyword and uses its Add
and Reverse
functions to perform some simple calculations. Note that the functions in the myutils
package are accessed using the package name (myutils
) followed by a dot (.
) and the function name (Add
or Reverse
).