An example package in Golang

In Go, a package is a collection of related Go source code files that are compiled together to form a single binary executable or library. Packages can be used to organize code and promote code reuse across projects. A package can be a standalone program or can be used as a library by other programs.

Here is an example package in Go:

package math

// Returns the sum of two integers
func Add(x, y int) int {
return x + y
}

// Returns the product of two integers
func Multiply(x, y int) int {
return x * y
}

This package, called math, defines two functions Add and Multiply. These functions take two integer arguments and return the sum and product of the two integers, respectively. The package can be used in other Go programs by importing it using the import keyword, like this:

import “math”

func main() {
x := 5
y := 10
sum := math.Add(x, y)
product := math.Multiply(x, y)
fmt.Printf(“Sum: %d\nProduct: %d\n”, sum, product)
}

This code imports the math package and calls its Add and Multiply functions to perform arithmetic operations on two integers. The output of the program will be:

makefile

Sum: 15
Product: 50

Practice Questions on packages in Golang

Here are some practice questions on packages in Go:

What is a package in Go?

A. A collection of related Go source code files
B. A collection of executable files
C. A collection of configuration files
D. A collection of data files

Answer: A

What is the keyword used to import a package in Go?

A. package
B. include
C. import
D. require

Answer: C

Which of the following is an example of a package in Go?

A. func main() {}
B. var x int = 5
C. type MyStruct struct {}
D. package math

Answer: D

Which of the following is a benefit of using packages in Go?

A. Packages make code less reusable
B. Packages make code more difficult to organize
C. Packages promote code reuse and organization
D. Packages increase code duplication

Answer: C

What is the purpose of the import keyword in Go?

A. To declare a variable
B. To define a function
C. To import a package
D. To allocate memory

Answer: C

Allocation in Golang
Arithmetic operators in Golang

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?