현재 3권의 신간들인 Go Optimizations 101, Go Details & Tips 101Go Generics 101이 출간되어 있습니다. Leanpub 서점에서 번들을 모두 구입하시는 방법이 비용 대비 효율이 가장 좋습니다.

Go에 대한 많은 정보들과 Go 101 책들의 최신 소식을 얻으시려면 Go 101 트위터 계정인 @Go100and1을 팔로잉 해주세요.

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 프로젝트는 Github 에서 호스팅됩니다. 오타, 문법 오류, 부정확한 표현, 설명 결함, 코드 버그, 끊어진 링크와 같은 모든 종류의 실수에 대한 수정 사항을 제출하여 Go 101을 개선을 돕는 것은 언제나 환영합니다.

주기적으로 Go에 대한 깊이 있는 정보를 얻고 싶다면 Go 101의 공식 트위터 계정인 @go100and1을 팔로우하거나 Go 101 슬랙 채널에j가입해주세요.

이 책의 디지털 버전은 아래와 같은 곳을 통해서 구매할 수 있습니다.
Go 101의 저자인 Tapir는 2016년 7월부터 Go 101 시리즈 책들을 집필하고 go101.org 웹사이트를 유지 관리하고 있습니다. 새로운 콘텐츠는 책과 웹사이트에 수시로 추가될 예정입니다. Tapir는 인디 게임 개발자이기도 합니다. Tapir의 게임을 플레이하여 Go 101을 지원할 수도 있습니다. (안드로이드와 아이폰/아이패드용):
  • Color Infection (★★★★★), 140개 이상의 단계로 이루어진 물리 기반의 캐주얼 퍼즐 게임
  • Rectangle Pushers (★★★★★), 2가지 모드와 104개 이상의 단계로 이루어진 캐주얼 퍼즐 게임
  • Let's Play With Particles, 세가지 미니 게임이 있는 캐주얼 액션 게임
페이팔을 통한 개인 기부도 환영합니다.

색인: