Introduction Of Source Code Elements

Go is known for its simple and clean syntax. This article will introduce the common source code elements in programming and show a simple Go program so that new gophers (Go programmers) will get a basic impression of Go code and how all kinds of code elements are used in Go code.

Programming And Source Code Elements

Simply speaking, programming can be viewed as manipulating all kinds of operations in all kinds of ways, to reach all kinds of goals. Operations write data to and read data from all kinds of hardware devices to complete all kinds of tasks. For modern computers, elemental operations are low-level instructions, such as 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 programing languages make some encapsulations for low-level operations, and make some abstracts for data, to make programing 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 them as special operations. The syntax of these control flows is close to human languages so that the code written by one programmers is easy to be understood by others.

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 quantity 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 mistake prone, many values are named. Such values include variables and named constants.

Named functions, named types and named values (including variables and named constants) are called resources in Go 101. The names of resources 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 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) resources 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 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 package name of the current source file.

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

const MaxRand = 16 // a named constant declaration.

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

// The main function is the entry function of this program.
func main() {
	var num = 100
	// Call StatRandomNumbers and two built-in functions.
	x, y := StatRandomNumbers(num) // a short variable declaration.
	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, the words with blue color are keywords (JavaScript needs to be enabled to colorize the code). Most other words in the program are identifiers. Please read keywords and identifiers for more information about keywords and identifiers.

The green int words at line 13 and line 14 denote the built-in int type, one of many kinds of integer types in Go. The 16 at line 5, 0 at line 15, 1 at line 17 and 100 at line 27 are some integer literals. The "Result: " at line 30 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 17 is an assignment. Line 5 declares a named constant, MaxRand. Line 14 and line 27 declare three variables, with the standard variable declaration form. Variables i at line 15, x and y at line 29 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 15 and 16, the equal-to operator == at line 31, and the addition operator + at line 17 and line 31. Yes, + at line 30 is not an operator, it is part of 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 30 and line 31, two built-in functions, print and println, are called. A custom function StatRandomNumbers is declared from line 13 to line 23, and it is called at line 29. Line 16 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. The function Intn declared in this standard package is called at line 16. 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 controls 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(numRands int) (int, int)
{ // syntax error
	var a, b int
	for i := 0; i < numRands; i++
	{ // syntax error
		if rand.Intn(MaxRand) < MaxRand/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.

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