CodeGo

Learn The Go Programming Language — Basics


Are you looking for a simple programming language that compiles quickly? A fast-running program? You can distribute your work easily that way. Then you’re ready to learn Go.

The Go programming language focuses on simplicity and speed. The language is simpler than other languages, so it’s easier to learn. Furthermore, it makes your programs run faster by harnessing the power of today’s multicore computers.

Go was designed with the following goals for a new language.

  • Fast compilation.
  • Code that is less cumbersome.
  • With garbage collection, unneeded memory is automatically freed.
  • Multi-tasking software that is easy to write (concurrency)
  • Multicore processors are well supported.

The Go Playground

The easiest way to try Go is to visit https://go.dev/play in your web browser. 

  1. Open https://go.dev/play in your browser.

2. Choose a simple Hello World program from the drop-down menu.

3. By clicking the Format button, your code will be automatically formatted according to Go conventions. Doing so is optional but a good practice.

4. Click the Run button.

The output is displayed at the bottom of the screen.

You have just run your first Go program, congratulations.

Code Walkthrough

Every Go file begins with a package clause. Packages are collections of code that perform similar tasks, such as formatting strings or performing math operations. A package clause identifies the package in which this file’s code will be included. If this code is to be run from the terminal, we need the special package main.

Next, Go files almost always contain import statements. The code in each file must import other packages before it can use the code in those other packages.

Each Go file ends with a code section, which is often divided into several functions. The concept of a function is that it is a group of one or more lines of code that can be called from other places in your program. In Go, the main function is run first when the program is run, which is why the function is named main.

Calling Functions

Hello World includes a call to the Println function in the fmt package. Having imported the package, we can access any functions it offers by typing the package name, a dot, and the function name.

To import multiple packages, we use an alternative import statement format that allows you to list multiple packages within parenthesis, one per line.

import (
"fmt"
"math"
)

Types

String

A string has been passed to the Println function as an argument. An array of bytes that represents text characters is referred to as a string. By using string literals, you can define strings directly within your code, a text between double quotes that Go will treat as a string.

"Hello, World!"

An escape sequence, a backslash followed by another character, can represent characters like newlines, tables, etc in strings.

+-----------------+-----------------------+
| Escape sequence | Value |
+-----------------+-----------------------+
| \n | A newline character |
| \t | A tab character |
| \" | Double quotation mark |
| \\ | A backslash |
+-----------------+-----------------------+

Runes

A string represents a whole series of text characters, but a rune represents a single character.

Rune literals are written with single quotation marks (‘), while string literals are surrounded by double quotation marks (“).

If you pass a rune to fmt.Println, you will see that numeric code in the output, not the original rune.

Booleans

There are only two possible values for a Boolean value: true or false.

Numbers

There are different types of numbers in Go, such as integers and floating points.

Statically typed

As a statically typed language, Go knows what the types of your values are even before your program runs. Functions expect their arguments to be of a particular type and their return values to have a type as well.

Go is statically typed. If you use the wrong type of value in the wrong place, Go will let you know.

A value’s type can be determined by passing it to the TypeOf function of the reflect package.

https://www.learncsdesign.com/media/1ef990da9e23754fad1e5796b8505cc2
// output
string
float64
int
bool

Declaring Variables

Variables are pieces of storage that contain values in Go. Variable declarations allow you to name variables. Use the var keyword followed by the variable’s name and the types of values it will hold.

var count int
var total, amount float64
var name string

Once you declare a variable, you can assign any value of that type.

count = 100
name = "Go"

Multiple variables can be assigned values in the same statement. Put the variable names on the left side of the = and the values on the right side, separated by commas.

total, amount = 100.00, 50.00

You can declare variables and assign them values on the same line if you know what their value will be beforehand.

var count int = 10

The variable type can usually be omitted from the declaration if you assign a value to the variable at the same time it is declared.

var count = 10

Zero Values

When you declare a variable without assigning it a value, it will contain the zero value of its type. The zero value for numeric types is 0, for string variables is an empty string, and for bool variables is false.

Short Variable Declarations

It’s more common to use a short variable declaration if you know what a variable’s initial value will be right away. You can use := instead of declaring the variable’s type and assigning it later with =.

count := 10

Naming Rules

The names of variables, functions, and types in Go follow a simple set of rules.

  • Names must begin with a letter, and they can contain any number of letters or numbers.
  • A variable, function, or type named with a capital letter is considered exported and can be accessed from other packages.
  • Variables/functions/types with lowercase names are considered unexported and can only be accessed within the current package.
  • Variables, functions, and types should be named in camel case.

Only variables, functions or types whose names begin with a capital letter are considered exported, accessible from package outside the current package.

Installing Go

It’s better to install Go on your computer if you would like to experiment with the Go language beyond Go Playground.

Install Go by following the instructions on https://go.dev/dl. At the command prompt, type go version to confirm Go has been installed.

Let’s write a hello world program in Go and compile it to generate an executable file that we can run.

  1. Open text editor and create hello_world.go file and copy the below code.
https://www.learncsdesign.com/media/e3056f2309058c3c436d91cb3efdc92a

2. Open terminal and change to directory where hello_world.go is present.

3. Run go fmt hello_world.go to clean up the code formatting.

$ go fmt hello_world.go

4. Run go build hello_world.go to compile the source code.

$ go build hello_world.go

5. Run the executable file hello_world.exe (if on windows)

$ hello_world.exe
Hello World

Go Tools

When you install go, it adds an executable named go to your command prompt.

Summary

  • Packages are collections of related functions and code.
  • It is necessary to import a package before you can use its functions within a Go file.
  • Usually, strings represent text characters as a series of bytes.
  • An individual text character is represented by a rune.
  • There are two most common numeric types in Go: int, which holds integers, and float64, which holds floating-point numbers.
  • A bool type holds true or false Boolean values.
  • Variables are pieces of storage that can store values of a specific type.
  • Variables will contain zero values if no value is assigned to them.
  • The := short variable declaration allows you to declare a variable and assign a value at the same time.
  • The name of a variable, function, or type must begin with a capital letter in order to be accessed from other packages.
  • The Go fmt command automatically formats source files according to Go standard formatting.
  • The go build command compiles Go source code into a binary format that computers can execute.
  • Using the go run command, a program is compiled and run without saving an executable file.

References:

https://go.dev/doc

Leave a Reply

Your email address will not be published.