Hello, future programmers! Are you ready to dive into a new programming adventure? Today, we'll be taking a look at the basics of Go programming — syntax and comments — where you'll write your first, simple Go program.
Go, also known as Golang, is a statically typed, compiled language developed at Google. It's known for its simplicity, efficiency, and ease of use. Notably, Go is widely used for concurrent programming, thanks to its advanced features such as Goroutines and Channels.
Just as English has rules that we call grammar, Go has its own set of regulations known as syntax. Let's get started!
In Go, we use statements to perform actions. These are usually terminated by a new line or a semicolon (;). The semicolon in the end of the statement is optional and used rarely. Go uses curly braces ({ }) to group statements into blocks.
Take a look at this simple Go syntax example:
In this example, package main specifies that it's the main entry point of the Go application. import "fmt" instructs Go to use the fmt library for formatted I/O operations, and in the main function, we print "Hello, Go World!". Though you may not fully understand this code just yet, we will explore each part of it step-by-step in forthcoming lessons.
Similar to other programming languages, Go supports two kinds of comments: single-line comments and multi-line comments. Single-line comments begin with //, while multi-line comments are surrounded by /* */. Comments provide documentation and critical reference points within the code and don't affect the program execution. They are meant to make the codebase understandable and easy to work with.
Here's an example of how you can use comments in your Go programs:
Now that we've covered the basics, let's delve deeper into the first Go program you'll write! Here is a simple Go program we have already encountered:
Let's understand each part of the program:
package main: This line declares the name of the package that this file resides in, which in this case ismain. Themainpackage is special inGo. It defines an executable program, rather than a library.import "fmt": This statement imports another package into the current package. The packagefmtprovides functionalities for formatted input/output.func main() { }:This line defines the main function of the program, which is executed when we run ourGoprogram. Similar to Java'spublic static void main(String[] args), the main function inGoserves as the entry point for the program.fmt.Println("Hello, Go World!"): This is a function call tofmt.Println(), which prints out the passed string to the console.
