The Wayback Machine - https://web.archive.org/web/20240718024723/https://www.geeksforgeeks.org/packages-in-golang/
Open In App

Packages in Golang

Last Updated : 20 Nov, 2019
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Packages are the most powerful part of the Go language. The purpose of a package is to design and maintain a large number of programs by grouping related features together into single units so that they can be easy to maintain and understand and independent of the other package programs. This modularity allows them to share and reuse. In Go language, every package is defined with a different name and that name is close to their functionality like “strings” package and it contains methods and functions that only related to strings.

Important Points

1. Import paths: In Go language, every package is defined by a unique string and this string is known as import path. With the help of an import path, you can import packages in your program. For example:

import "fmt"

This statement states that you are importing an fmt package in your program. The import path of packages is globally unique. To avoid conflict between the path of the packages other than the standard library, the package path should start with the internet domain name of the organization that owns or host the package. For example:

import "geeksforgeeks.com/example/strings"

2. Package Declaration: In Go language, package declaration is always present at the beginning of the source file and the purpose of this declaration is to determine the default identifier for that package when it is imported by another package. For example:

package main

3. Import declaration: The import declaration immediately comes after the package declaration. The Go source file contains zero or more import declaration and each import declaration specifies the path of one or more packages in the parentheses. For example:

// Importing single package
import "fmt"

// Importing multiple packages
import(
"fmt"
"strings"
"bytes"
) 

When you import a package in your program you’re allowed to access the members of that package. For example, we have a package named as a “sort”, so when you import this package in your program you are allowed to access sort.Float64s(), sort.SearchStrings(), etc functions of that package.

4. Blank import: In Go programming, sometimes we import some packages in our program, but we do not use them in our program. When you run such types of programs that contain unused packages, then the compiler will give an error. So, to avoid this error, we use a blank identifier before the name of the package. For example:

import _ "strings"

It is known as blank import. It is used in many or some occasions when the main program can enable the optional features provided by the blank importing additional packages at the compile-time.

5. Nested Packages: In Go language, you are allowed to create a package inside another package simply by creating a subdirectory. And the nested package can import just like the root package. For example:

import "math/cmplx"

Here, the math package is the main package and cmplx package is the nested package.

6. Sometimes some packages may have the same names, but the path of such type of packages is always different. For example, both math and crypto packages contain a rand named package, but the path of this package is different, i.e, math/rand and crypto/rand.

7. In Go programming, why always the main package is present on the top of the program? Because the main package tells the go build that it must activate the linker to make an executable file.

Giving Names to the Packages

In Go language, when you name a package you must always follow the following points:

  • When you create a package the name of the package must be short and simple. For example strings, time, flag, etc. are standard library package.
  • The package name should be descriptive and unambiguous.
  • Always try to avoid choosing names that are commonly used or used for local relative variables.
  • The name of the package generally in the singular form. Sometimes some packages named in plural form like strings, bytes, buffers, etc. Because to avoid conflicts with the keywords.
  • Always avoid package names that already have other connotations. For example:

Example:




// Go program to illustrate the
// concept of packages
// Package declaration
package main
  
// Importing multiple packages
import (
    "bytes"
    "fmt"
    "sort"
)
  
func main() {
  
    // Creating and initializing slice
    // Using shorthand declaration
    slice_1 := []byte{'*', 'G', 'e', 'e', 'k', 's', 'f',
        'o', 'r', 'G', 'e', 'e', 'k', 's', '^', '^'}
    slice_2 := []string{"Gee", "ks", "for", "Gee", "ks"}
  
    // Displaying slices
    fmt.Println("Original Slice:")
    fmt.Printf("Slice 1 : %s", slice_1)
    fmt.Println("\nSlice 2: ", slice_2)
  
    // Trimming specified leading
    // and trailing Unicode points
    // from the given slice of bytes
    // Using Trim function
    res := bytes.Trim(slice_1, "*^")
    fmt.Printf("\nNew Slice : %s", res)
  
    // Sorting slice 2
    // Using Strings function
    sort.Strings(slice_2)
    fmt.Println("\nSorted slice:", slice_2)
}


Output:

Original Slice:
Slice 1 : *GeeksforGeeks^^
Slice 2:  [Gee ks for Gee ks]

New Slice : GeeksforGeeks
Sorted slice: [Gee Gee for ks ks]


Previous Article
Next Article

Similar Reads

How to convert a slice of bytes in uppercase in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to convert a slice in the uppercase usin
2 min read
Golang program that uses fallthrough keyword
With the help of fallthrough statement, we can use to transfer the program control just after the statement is executed in the switch cases even if the expression does not match. Normally, control will come out of the statement of switch just after the execution of first line after match. Don't put the fallthrough in the last statement of switch ca
2 min read
math.Lgamma() Function in Golang with Examples
Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. This package provides Lgamma() function which is used to find the natural logarithm and sign (either -1 or +1) of Gamma(a). So, you need to add a math package in your program with the help of th
2 min read
math.Float64bits() Function in Golang With Examples
Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. This package provides Float64bits() function which returns the IEEE 754 binary representation of a with the sign bit of a and the result in the same bit position. So, you need to add a math pack
2 min read
How to check equality of slices of bytes in Golang?
In Go language slice is more powerful, flexible, and convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence that stores elements of a similar type, you are not allowed to store different types of elements in the same slice. In the Go slice of byes, you are allowed to check the equality of the slices w
3 min read
atomic.AddInt64() Function in Golang With Examples
In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The AddInt64() function in Go language is used to automatically add delta to the *addr. This function is defined under the atomic package. Here, you need to import "sync/atomic" package in order to use these functions. Syntax
3 min read
atomic.StoreInt64() Function in Golang With Examples
In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The StoreInt64() function in Go language is used to atomically store val into *addr. This function is defined under the atomic package. Here, you need to import "sync/atomic" package in order to use these functions. Syntax: f
2 min read
reflect.FieldByIndex() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.FieldByIndex() Function in Golang is used to get the nested field corresponding to index. To access this function, one needs to imports the reflect package in the
2 min read
strings.Contains Function in Golang with Examples
strings.Contains Function in Golang is used to check the given letters present in the given string or not. If the letter is present in the given string, then it will return true, otherwise, return false. Syntax: func Contains(str, substr string) bool Here, str is the original string and substr is the string that you want to check. Let us discuss th
2 min read
bits.Sub() Function in Golang with Examples
The bits.Sub() Function in Golang is used to find the difference of a, b and borrow, i.e. diff = a - b - borrow. Here the borrow must be 0 or 1; otherwise, the behavior is undefined. To access this function, one needs to imports the math/bits package in the program. The return value of the borrowOutput will be always 0 or 1 in any case. Syntax: fun
2 min read
Article Tags :
three90RightbarBannerImg