How to Sort a Slice in Golang

In the Go language, you can sort a slice using the “Slice()” function. This function sorts the specified slice given the provided less function. Syntax func Slice(a_slice interface{}, less func(p, q int) bool) Example package main import ( “fmt” “sort” ) func main() { // Define a slice of integers. nums := []int{51, 21, 16, … Read more

Golang Logging: A Step-by-step Guide

To create a log in Golang, you can use the built-in “log” library. The package log in Go implements the simple logging package that defines a type, Logger, with methods for formatting output. You can use these rough-and-ready logs for local development in which you need to get fast feedback from your code may be … Read more

How to Write a File in Golang

To write a file in Golang, you can use the “io.WriteString()” function. The “os.Create()” function creates or truncates a file and the io.Writer interface provides a way to write data to the file. The os.File type implements the io.Writer interface, so you can use it directly to write data to the file. Example package main … Read more

How to Open a File in Golang

To open a file in Golang, you can use the “os.OpenFile()” function.  The os.Open() function takes a filepath, flag, and file mode as arguments and opens and reads the file. Syntax os.OpenFile(name/path string, flag int, perm FileMode) Parameters name: The first parameter is a file name, which is the complete file path of that file. … Read more

Golang os.Create() Method

Golang os.Create() function is used to create a file. The Create() function creates a new file if it does not exist, with the file mode 0666 for reading and writing. The Create() function truncates the file if it exists, meaning its contents are removed without deleting it. The returned file descriptor is open for reading and … Read more

How to Delete or Remove File in Go

To delete a file in Golang, you can “use the os.Remove() function.” The os.Remove() function is “used to delete a file or directory identified by a file path.” The file or directory path you want to remove is the only argument for this function. If there is an error, that will be of type *PathError. … Read more

How to Convert a String to Byte Array in Go

To convert a string to a byte array in Go, you can “use the []byte() function”. The byte() function accepts a string as input and returns the array.  Syntax []byte(input_string) Parameters input_string: We pass a string to the byte slice. Return value It returns the bytes of all the characters of the string. Example 1: Converting … Read more

Strings in Golang

Golang string is a “sequence of variable-width characters where every character is represented by one or more bytes using UTF-8 Encoding.” In other words, strings are the immutable chain of arbitrary bytes(including bytes with zero value), or string is a read-only slice of bytes, and the bytes of the strings can be represented in the … Read more

How to Convert a Slice to String in Golang

To convert a slice to a string in Golang, you can use the “strings.Join()” function. The conversion doesn’t change the original data. The only difference between string and byte slice is that the strings are immutable, while byte slices can be modified. package main import ( “fmt” “reflect” “strings” ) func main() { str1 := … Read more

What is the rune type in Golang

A rune in Go is a “data type that stores codes that represent Unicode characters.” Unicode is the collection of all possible characters present in the whole world. Golang rune literals are 32-bit integer values (however, they are untyped constants, so their type can change). They represent the Unicode codepoints. “Rune” means Unicode codepoint. (think … Read more

Golang Custom Type Declaration

In Go, you can create “custom types using type declarations”. A custom type is a user-defined type based on an existing one. You can create custom types to make your code more expressive, readable, and easier to maintain. To define a custom type declaration in Golang, you can use the “type” keyword. Example 1: Defining … Read more

Golang Receiver Function

A receiver function in Go is “defined within a type.” The receiver function is associated with the type and can only be called on instances of that type. To define a receiver function, specify the receiver type in parentheses before the function name. The receiver is usually a pointer to the type, allowing you to … Read more

Arrays in Golang

Golang Arrays store multiple values of the same type in a single variable instead of declaring separate variables for each value. How to declare an array in Golang To declare an array in Golang, specify the type of elements and the number of items required by an array. An array belongs to type n[T]. The n … Read more

How to Install Golang on Mac

Follow these steps to install Golang on Mac: Download the latest version of Go for your platform here: https://go.dev/dl/. Follow the instructions for your platform to install the Go tools: https://go.dev/doc/install#install. It is recommended to use the default installation settings. On Mac OS X and Linux, Go is default installed to directory /usr/local/go, and the GOROOT environment … Read more

How to Serialize JSON String in Go

To serialize json string in Go, you can “use the json.Marshal()” function to a slice of bytes. You can deserialize a slice of bytes into a Golang value using the “json.Unmarshal()” function. Syntax func Marshal(v interface{}) ([]byte, error) If Marshal() fails to serialize the input value, it will return a non-nil error. Few things you … Read more

Golang make() Function

Golang make() function is “used for slices, maps, or channels.” The make() function allocates memory on the heap and initializes and puts zero or empty strings into values. The make() function assigns the underlying array with a size equal to the given capacity and returns the slice, which refers to the underlying array. Syntax func … Read more

Golang strings.Contains() Function

Golang strings.Contains() function is “used to check the given letters present in the given string or not.” If the letter is present in the given string, it will return true; otherwise, return false. Syntax func Contains(s, substr string) bool Parameters s: The first parameter is a source string, and substr: The second is the substring, … Read more

Golang maps

Golang Maps is a collection of unordered pairs of key-value. It is widely used because it provides fast lookups and values that can retrieve, update or delete with the help of keys. Declaration and initialization of Maps in Go map[KeyType]ValueType KeyType may be any comparable type (more on this later), and ValueType may be any type, … Read more

TypeCasting in Golang

Typecasting in Golang refers to the process of converting a value of one type to another type. This conversion can be done automatically or explicitly by the programmer. For example, you can typecast long to int if you want to save the long value into a simple integer. You can convert the values from one … Read more

How to Convert String to Int64 in Golang

To convert string to int64 in Golang, you can “use the strconv.ParseInt() method”. The strconv.ParseInt() function is used to convert a “decimal string (base 10) and checks that it fits into a 64-bit signed integer”. Example 1: Using ParseInt() function to convert string to int64 package main import ( “fmt” “strconv” ) func main() { … Read more

How to Convert JSON to Map in Golang

To convert a json to a map in Golang, you can use the “json.Unmarshal()” function and pass the JSON string as “bytearray” and the “address of an empty map” as arguments to the function. The json.Unmarshal() method parses the JSON-encoded data and stores the result in the value pointed to by the interface. If an … Read more

Golang fmt.Sprintf() Function

Golang fmt.Sprintf() function is “used to format according to a format specifier and returns the resulting string.” Syntax func Sprintf(format string, a …interface{}) string Parameters format string: This includes some variables along with some strings. a …interface{}: This is the specified constant variable. Return Value The Sprintf() function returns a String and does not print the … Read more

Golang strings.ContainsRune() Function

Golang strings.ContainsRune() function is “used to check whether the given string contains the specified rune or not in it.” Syntax func ContainsRune(s string, r rune) bool Parameters The function takes two parameters. s: It is the string. r: It is the s rune. The return type of the function is bool. Return value It returns … Read more

Golang strings.EqualFold() Function

Golang strings.EqualFold() function is “used to check if two strings are equal.” The comparison is not case-sensitive. Syntax func EqualFold(s, t string) bool Parameters s: It is the first string. t: It is the second string. Return value The EqualFold() function returns true if both string arguments are equal (under Unicode case-folding). Otherwise, false is … Read more

Golang strings.ContainsAny() Function

Golang strings.ContainsAny() function is “used to check whether any Unicode code points in characters are present in the string.” Syntax func ContainsAny(str, charstr string) bool Parameters str: It is the first parameter is a string, and the second is a character we need to check inside the string. string:  It is a set of values; … Read more

Golang strings.Index() Function

Golang strings.Index() function is “used to get the first instance of a specified substring.” If the substring is not found, then this method will return -1. Syntax func Index(s, substr string) int Parameters s: It is the original string. substr: It is a string we want to find the index value. Return Value The Index() function … Read more

Golang strings.Join() Method

Golang strings.Join() is “used to concatenate all the elements present in the slice of string into a single string.” Syntax func Join(s []string, seperator string) string Parameter s: It is the string from which we can concatenate elements. separator: It is placed between the elements in the final string. Return value It returns a string. … Read more

Golang strings.Fields() Function

Golang string.Fields() function is “used to splits the given string around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace() function, returning a slice of substrings of string or an empty slice if str contains only white space.” Syntax func Fields(s string) []string Parameters s: The Fields() function takes the string … Read more

How to Compare Two Slices in Golang

To compare two slices for equality in Golang, you need to “write a user-defined function that iterates over both slices and compares their elements one by one”. The slices are considered equal if they have the same length and all their corresponding elements are equal. Method 1: Using a user-defined function We will compare elements … Read more

How to Copy an Array into Another Array in Golang

Golang does not provide a specific built-in function to copy one array into another array. But we can create a copy of an array by simply assigning an array to a new variable by value or by reference. Syntax // creating a copy of an array by value arr := arr1 // Creating a copy … Read more

How to Convert String to Rune in Go

To convert a string to a rune in Golang, you can use the “[]rune()”. A rune is a single Unicode code point. A string is a sequence of runes. Syntax []rune(s) Example package main import ( “fmt” ) func main() { // Define a string s := “Hi, Golang!” // Convert the string to a … Read more

How to Convert String to Float in Golang

To convert a string to float in Go, you can use the “strconv.ParseFloat()” function. The string.ParseFloat() method is “used to accept decimal and hexadecimal floating-point numbers”. If the string is well-formed and near a valid floating-point number, the “ParseFloat()” function returns the nearest floating-point number rounded using IEEE754 unbiased rounding. Syntax func ParseFloat(s string, bitSize … Read more

How to Convert JSON to CSV in Golang

To convert JSON to CSV in Golang, decode the JSON data with the json.Decoder and encoding/csv package to write the output CSV data using csv.Writer. First, you will need to unmarshal the JSON data into a suitable data structure (like a slice of structs or a slice of maps), and then you can write that … Read more

Scope of Variables in Golang

The scope of a variable in Golang can be defined as a part of the program where a particular variable is accessible. Golang scope rules of variables can be divided into two categories which depend on where the variables are declared: Local Variables (Declared Inside a block or a function) Global Variables (Declared outside a … Read more

Golang Encryption Decryption: How to Create AES Encryption

Encryption is the process of converting the plaintext to ciphertext. In simpler terms, encryption takes readable data and alters it to appear random. Encryption requires an encryption key: a set of mathematical values that both the sender and the receiver of the encrypted message know. If you have seen the movie Imitation Game, you will … Read more

How to Make HTTP Requests in Golang

To make HTTP requests in Go, you can use the “net/http” package from the standard library. You will make a GET request using the default Go HTTP client. Then, you will enhance your program to make a POST request with a body. Finally, you will customize your POST request to include an HTTP header and … Read more

How to Use the Flag Package in Go

Golang has a built-in flag package that enables one to parse command-line flags. The flag package allows you to define String, Bool, or Int flags. Syntax flag.Int(“n”, def_val, description) Parameters n: the variable to be parsed. def_val: the default value of the variable. description: the description of the flag. Example package main import ( “flag” … Read more