Three new books, Go Optimizations 101, Go Details & Tips 101 and Go Generics 101 are published now. It is most cost-effective to buy all of them through this book bundle in the Leanpub book store.

Introduction to Source Code Elements

Go is known for its simple and clean syntax. This article introduces the common source code elements in programming through a simple example. This will help new gophers (Go programmers) get a basic idea of the usage of Go elements.

Programming and Source Code Elements

Programming can be viewed as manipulating operations in all kinds of ways to reach certain goals. Operations write data to and read data from hardware devices to complete tasks. For modern computers, elemental operations are low-level CPU and GPU instructions. Common hardware devices include memory, disk, network card, graphics card, monitor, keyboard and mouse, etc.

Programming by manipulating low-level instructions directly is tedious and error-prone. High-level programming languages make some encapsulations for low-level operations, and make some abstracts for data, to make programming more intuitive and human-friendly.

In popular high-level programming languages, operations are mainly achieved by calling functions and using operators. Most popular high-level programming languages support several kinds of conditional and loop control flows, we can think of them as special operations. The syntax of these control flows is close to human language so that the code written by programmers is easy to understand.

Data is abstracted as types and values in most high-level programming languages. Types can be viewed as value templates, and values can be viewed as type instances. Most languages support several built-in types, and also support custom types. The type system of a programming language is the spirit of the language.

There may be a large number of values used in programming. Some of them can be represented with their literals (text representations) directly, but others can't. To make programming flexible and less error-prone, many values are named. Such values include variables and named constants.

Named functions, named values (including variables and named constants), defined types and type alias are called code elements. The names of code elements must be identifiers. Package names and package import names shall also be identifiers.

High-level programming code will be translated to low-level CPU instructions by compilers to get executed. To help compilers parse high-level programming code, many words are reserved to prevent them from being used as identifiers. Such words are called keywords.

Many modern high-level programming languages use packages to organize code. A package must import another package to use the exported (public) code elements in the other package. Package names and package import names shall also be identifiers.

Although the code written in high-level programming languages is more understandable than low-level machine languages, we still need some comments for some code to explain the logic. The example program in the next section contains many comments.

A Simple Go Demo Program

Let's view a short Go demo program to know all kinds of code elements in Go. Like some other languages, in Go, line comments start with //, and each block comment is enclosed in a pair of /* and */.

Below is the demo Go program. Please read the comments for explanations. More explanations are following the program.
package main // specify the source file's package

import "math/rand" // import a standard package

const MaxRnd = 16 // a named constant declaration

// A function declaration
/*
 StatRandomNumbers produces a certain number of
 non-negative random integers which are less than
 MaxRnd, then counts and returns the numbers of
 small and large ones among the produced randoms.
 n specifies how many randoms to be produced.
*/
func StatRandomNumbers(n int) (int, int) {
	// Declare two variables (both as 0).
	var a, b int
	// A for-loop control flow.
	for i := 0; i < n; i++ {
		// An if-else control flow.
		if rand.Intn(MaxRnd) < MaxRnd/2 {
			a = a + 1
		} else {
			b++ // same as: b = b + 1
		}
	}
	return a, b // this function return two results
}

// "main" function is the entry function of a program.
func main() {
	var num = 100
	// Call the declared StatRandomNumbers function.
	x, y := StatRandomNumbers(num)
	// Call two built-in functions (print and println).
	print("Result: ", x, " + ", y, " = ", num, "? ")
	println(x+y == num)
}
Save above source code to a file named basic-code-element-demo.go and run this program by:
$ go run basic-code-element-demo.go
Result: 46 + 54 = 100? true

In the above program, package, import, const, func, var, for, if, else, and return are all keywords. Most other words in the program are identifiers. Please read keywords and identifiers for more information about keywords and identifiers.

The four int words at line 15 and line 17 denote the built-in int type, one of many kinds of integer types in Go. The 16 at line 5, 0 at line 19, 1 at line 22 and 100 at line 32 are some integer literals. The "Result: " at line 36 is a string literal. Please read basic types and their value literals for more information about above built-in basic types and their value literals. Some other types (composite types) will be introduced later in other articles.

Line 22 is an assignment. Line 5 declares a named constant, MaxRnd. Line 17 and line 32 declare three variables, with the standard variable declaration form. Variables i at line 19, x and y at line 34 are declared with the short variable declaration form. We have specified the type for variables a and b as int. Go compiler will deduce that the types of i, num, x and y are all int, because they are initialized with integer literals. Please read constants and variables for more information about untyped values, type deduction, value assignments, and how to declare variables and named constants.

There are many operators used in the program, such as the less-than comparison operator < at line 19 and 21, the equal-to operator == at line 37, and the addition operator + at line 22 and line 37. Yes, + at line 36 is not an operator, it is one character in a string literal. The values involved in an operator operation are called operands. Please read common operators for more information. More operators will be introduced in other articles later.

At line 36 and line 37, two built-in functions, print and println, are called. A custom function StatRandomNumbers is declared from line 15 to line 28, and is called at line 34. Line 21 also calls a function, Intn, which is a function declared in the math/rand standard package. A function call is a function operation. The input values used in a function call are called arguments. Please read function declarations and calls for more information.

(Note, the built-in print and println functions are not recommended to be used in formal Go programming. The corresponding functions in the fmt standard packages should be used instead in formal Go projects. In Go 101, the two functions are only used in the several starting articles.)

Line 1 specifies the package name of the current source file. The main entry function must be declared in a package which is also called main. Line 3 imports a package, the math/rand standard code package. Its import name is rand. The function Intn declared in this standard package is called at line 21. Please read code packages and package imports for more information about how to organize code packages and import packages.

The article expressions, statements and simple statements will introduce what are expressions and statements. In particular, all kinds of simple statements, which are special statements, are listed. Some portions of all kinds of control flows must be simple statements, and some portions must be expressions.

In the StatRandomNumbers function body, two control flows are used. One is a for loop control flow, which nests the other one, an if-else conditional control flow. Please read basic control flows for more information about all kinds of basic control flows. Some other special control flows will be introduced in other articles later.

Blank lines have been used in the above program to improve the readability of the code. And as this program is for code elements introduction purpose, there are many comments in it. Except the documentation comment for the StatRandomNumbers function, other comments are for demonstration purpose only. We should try to make code self-explanatory and only use necessary comments in formal projects.

About Line Breaks

Like many other languages, Go also uses a pair of braces ({ and }) to form an explicit code block. However, in Go programming, coding style can't be arbitrary. For example, many of the starting curly braces ({) can't be put on the next line. If we modify the StatRandomNumbers function declaration in the above program as the following, the program will fail to compile.
func StatRandomNumbers(n int) (int, int)
{ // syntax error
	var a, b int
	for i := 0; i < n; i++
	{ // syntax error
		if rand.Intn(MaxRnd) < MaxRnd/2
		{ // syntax error
			a = a + 1
		} else {
			b++
		}
	}
	return a, b
}

Some programmers may not like the line break restrictions. But the restrictions have two benefits:
  1. they make code compilations become faster.
  2. they make the coding styles written by different gophers look similar, so that it is more easily for gophers to read and understand the code written by other gophers.

We can learn more about line break rules in a later article. At present, we should avoid putting a starting curly brace on a new line. In other words, generally, the first non-blank character of a code line should not be the starting curly brace character. (But, please remember, this is not a universal rule.)


Index↡

The Go 101 project is hosted on Github. Welcome to improve Go 101 articles by submitting corrections for all kinds of mistakes, such as typos, grammar errors, wording inaccuracies, description flaws, code bugs and broken links.

If you would like to learn some Go details and facts every serveral days, please follow Go 101's official Twitter account @go100and1.

The digital versions of this book are available at the following places:
Tapir, the author of Go 101, has been on writing the Go 101 series books and maintaining the go101.org website since 2016 July. New contents will be continually added to the book and the website from time to time. Tapir is also an indie game developer. You can also support Go 101 by playing Tapir's games (made for both Android and iPhone/iPad):
Individual donations via PayPal are also welcome.

Index: