Mastering Go: Unleashing the Power of Golang
Go, often referred to as Golang, is a statically typed, compiled programming language designed by Google. It was created to be efficient, readable, and productive for building reliable and scalable software systems. Go was developed with a focus on simplicity, performance, and concurrency.
What are the advantages of Go?
Some of the key advantages of Go:
- It executes fast
- Garbage collection
- Simpler object-oriented features: No inheritance, no constructors, no generics
- Efficient concurrency
- Management of task execution through Goroutines
- Communication between tasks through Channels
- Synchronization between tasks through Select
Go folder structure
The top level of a Golang project is called a Workspace, this is the directory where all the Go files are stored. A common organization of the folder structure is recommended to enhance sharing. The following 3 subfolders are recommended for a workspace:
src
: Contains the source code filespkg
: Contains librariesbin
: Contains the compiled executables
What is the Garbage collection in Golang?
Garbage collection is a set of different methods that handle the deallocation of objects that are no longer in use to recycle memory.
What does the βgoβ tool do?
The go
tool is a command line tool used to perform several tasks in Go. These are some of its common uses:
go build
: Compiles the program and creates an executable for the main packagego doc
: Prints the documentation for a packagego fmt
: Formats source code filesgo get
: Downloads packages and install themgo list
: Lists all installed packagesgo run
: Compiles and runs the executablego test
: Runs tests using files ending in_test.go
How do you work with pointers in Golang?
A pointer is an address to data stored in memory. The &
operator can be used to get the address of a variable or function, and the *
operator can be used to return the data stored at that address.
What is a tagless switch in Golang?
A tagless switch is a construct that enables switch
statements to be used as an alternative of long if-else
statements. Itβs named tagless because instead of the usual tag on the case
it contains a conditional. Hereβs an example:
switch {
case x > 1:
fmt.PrintF(βcase1β)
case x < -1:
fmt.PrintF(βcase2β)
default:
fmt.PrintF(βno matchβ)
}
When passing a struct as the argument on a function, which are good reasons to pass a pointer instead of the struct itself?
- The struct is very large, so passing the struct itself would create an entire copy in memory
- The function needs to modify the structure
What is a Variadic function in golang?
A Variadic function is a function which takes a varying number of arguments of one type. It is represented by ellipsis (3 dots β¦
) followed by the data type.
func something(values β¦int) {
for \_, v := range values {
fmt.Println(n)
}
}
References
- Official documentation: https://go.dev/doc/