Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. In a different way, encapsulation is a protective shield that prevents the data from being accessed by the code outside this shield.

In object-oriented languages, the variables or data of a class are hidden from any other class and can be accessed only through any member function of own class in which they are declared. But Go language does not support classes and objects. So, in the Go language, encapsulation is achieved by using packages. Go provides two different types of identifiers, i.e. exported and unexported identifiers. Encapsulation is achieved by exported elements(
variables,
functions,
methods, fields,
structures) from the packages, it helps to control the visibility of the elements(variables, functions, methods, fields, structures). The elements are visible if the package in which they are defined is available in your program.
1. Exported Identifiers: Exported identifiers are those identifiers which are exported from the package in which they are defined. The first letter of these identifiers is always in capital letter. This capital letter indicates that the given identifier is exported identifier. Exported identifiers are always limited to the package in which they are defined. When you export the specified identifier from the package you simple just export the name not the implementation of that identifier. This mechanism is also applicable for function, fields, methods, and structures.
Example:
C
// Go program to illustrate
// the concept of encapsulation
// using exported function
package main
import (
"fmt"
"strings"
)
// Main function
func main() {
// Creating a slice of strings
slc := []string{"GeeksforGeeks", "geeks", "gfg"}
// Convert the case of the
// elements of the given slice
// Using ToUpper() function
for x := 0; x < len(slc); x++ {
// Exported Method
res := strings.ToUpper(slc[x])
// Exported Method
fmt.Println(res)
}
}
Output:
GEEKSFORGEEKS
GEEKS
GFG
Explanation: In the above example, we convert the case of the elements of the
slc slice to uppercase by exporting
ToUpper() function from strings package.
res := strings.ToUpper(slc[x])
Here, the first letter of the
ToUpper() function is in uppercase, which indicates that this function is exported function. If you try to change the case of the
ToUpper() function into lowercase, then the compiler will give an error, as shown below:
res := strings.toUpper(slc[x])
Output:
./prog.go:22:9: cannot refer to unexported name strings.toUpper
./prog.go:22:9: undefined: strings.toUpper
So, this process(exporting of variables, fields, methods, functions, structures) is known as encapsulation. Due to encapsulation we only export the name of the function not the whole definition of the function in our program and the definition of the ToUpper() function is wrapped inside strings package, so for exporting ToUpper() function first you need to import strings package in your program.
2. Unexported Identifiers: Unexported identifiers are those identifiers which are not exported from any package. They are always in lowercase. As shown in the below example addition function is not related to any package, so it is an unexported function and the visibility of this method is limited to this program only.
Example:
C
// Go program to illustrate
// the unexported function
package main
import "fmt"
// The addition function returns
// the sum of the elements
// Unexported function
func addition(val ...int) int {
s := 0
for x := range val {
s += val[x]
}
fmt.Println("Total Sum: ", s)
return s
}
// Main function
func main() {
addition(23, 546, 65, 42, 21, 24, 67)
}
Output:
Total Sum: 788
Benefits of Encapsulation:
- Hiding implementation details from the user.
- Increase the reusability of the code.
- It prevents users from setting the function's variables arbitrarily. It only sets by the function in the same package and the author of that package ensure that the function maintain their internal invariants.
Similar Reads
Composition in Golang
Composition is a method employed to write re-usable segments of code. It is achieved when objects are made up of other smaller objects with particular behaviors, in other words, Larger objects with a wider functionality are embedded with smaller objects with specific behaviors. The end goal of compo
5 min read
Generics in Golang
Generics are essentially template/boilerplate code written in a form to use on the Go with types that can be added later. The main aim of generics is to achieve greater flexibility in terms of writing code with the addition of fewer lines. The concept of Generics has existed for a long time now and
4 min read
Type Assertions in Golang
Type assertions in Golang provide access to the exact type of variable of an interface. If already the data type is present in the interface, then it will retrieve the actual data type value held by the interface. A type assertion takes an interface value and extracts from it a value of the specifie
2 min read
Channel in Golang
In Go language, a channel is a medium through which a goroutine communicates with another goroutine and this communication is lock-free. Or in other words, a channel is a technique which allows to let one goroutine to send data to another goroutine. By default channel is bidirectional, means the gor
7 min read
flag.Bool() Function in Golang With Examples
Go language provides inbuilt support for command-line parsing and has functions that could be used to define flags to be used with a command-line program using the flag package. This package provides the flag.Bool() function which is used to define a boolean flag with the specified name, default val
2 min read
io.Pipe() Function in Golang with Examples
In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The Pipe() function in Go language is used to create a concurrent in-memory pipe and can be applied in order to link the code t
3 min read
io.Copy() Function in Golang with Examples
In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The Copy() function in Go language is used to copy from the stated src i.e, source to the dst i.e, destination till either the
3 min read
fmt.Scan() Function in Golang With Examples
In Go language, fmt package implements formatted I/O with functions analogous to C's printf() and scanf() function. The fmt.Scan() function in Go language scans the input texts which is given in the standard input, reads from there and stores the successive space-separated values into successive arg
2 min read
math.Inf() 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. You can find positive infinity (if sign >= 0) or negative infinity (if sign < 0) with the help of the Inf() function provided by the math
2 min read
bits.Len() Function in Golang with Examples
Go language provides inbuilt support for bits to implement bit counting and manipulation functions for the predeclared unsigned integer types with the help of bits package. This package provides Len() function which is used to find the minimum number of bits required to represent a and the result is
2 min read