This content originally appeared on DEV Community and was authored by Vignesh Muthukumaran
I recently started learning Go after going through a lot of articles talking about all the awesome features it has. Here, I will try to break down a simple Go program that prints a line to understand the anatomy of a Go program.
package main
import "fmt"
func main(){
fmt.Println("Hi there!")
}
First, let's understand how to run this program. The simple command below will run the program(Assuming the file is named main.go).
go run main.go
The Go CLI has a lot of other options as well. Let's just have a look at a few frequently used ones.
Command | Function |
---|---|
go build | Compiles go source code |
go run | Compiles and executes the go source code |
go fmt | Formats all code in the current directory |
go install | Compiles and installs a package |
go get | Downloads source code of other package |
go test | Run test cases associated with the project |
Go Packages
So, lets start with package main.
A package is a collection of common source code files. A package can have many related files. The only requirement is that every file should declare the package it belongs to in the first line.
But, why to call our package main?
There are 2 types of packages in Go, they are
- Executable - Generates a executable file
- Reusable - Generates Libraries, reusable code
The name of the package main makes it an executable package. If we had used any other name, it wouldn't have been an executable package. An executable package automatically executes the main function inside it. main here is a key word. Main package should have a main function. Also, if we build other packages, it wouldn't result in a executable file.
Import
Now, let's look at import "fmt"
import is used to make the functionality available in the library package to the current program we are executing.
fmt is a standard library package available with Go. It implements formatted I/O functions similar to C's printf and scanf.
We can get a list of all the packages available in Go at (https://pkg.go.dev/std).
Go Functions
Functions are declared with the key word func. The syntax is as follows,
func <name of function> (<comma seperated arguments>) {
<body of the function>
}
Structure of a Go program
All Go files follow the same pattern.
- Package Declaration
- Import statements
- Function definitions
Along this article, I hope you got a grip on the basics of Go. I will write a few more articles and will get into Go routines and all the powerful features in Go. Happy Coding!
This content originally appeared on DEV Community and was authored by Vignesh Muthukumaran
Vignesh Muthukumaran | Sciencx (2022-06-15T13:51:34+00:00) Anatomy of a Go Program. Retrieved from https://www.scien.cx/2022/06/15/anatomy-of-a-go-program/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.