The Art of Go - Basics: Introduction to Programming in Go: Read and Learn Programming
By Harry Yoon
()
About this ebook
Learn Golang Programming by "Reading" This Book!
Go is one of the most popular programming languages, created by Google. Go is much simpler than most other modern programming languages such as Java or C#. It is easier to learn. It is easier to use. And, it is more fun to use.
If you are just starting with programming, then Go is the perfect language to learn programming with. Go is a "backend programming language", and it is different from other popular dynamic languages like Python and Javascript. It requires more discipline. It will make you a better programmer. Once you are comfortable with Go, you can more easily learn other programming languages.
The Art of Go - Basics starts from the absolute basics and moves on to more advanced topics. Although it is an introductory book, you will gain sufficient knowledge, after reading this book, that you can venture into a journey of programming in Go on your own. If you are a seasoned developer, then it will provide a good introduction to idiomatic usages of Go in broad contexts.
Who is this book for?
- Anyone who wants to know what programming is and how the code is written.
- Anyone who has tried to learn programming and given up because it was too hard.
- Anyone who has some experience in programming and who wants to learn the Go language.
The Art of Go - Basics is organized into a series of small lessons. Each lesson starts with simple example programs, and it emphasizes code reading rather than premature writing. You will learn basics of coding, and some intricacies of Golang, just by reading each lesson. The book includes some (optional) exercises, and it ends with a few final projects.
The Art of Go - Basics covers the following topics (as of version Go 1.16), among other things:
- The basic structure of Go programs.
- Basic constructs of the Go programming language such as expressions and statements.
- Primitive types, slices, maps, and functions.
- Go structs, interfaces, and methods.
- Pointers. Value semantics vs reference semantics.
- Value receivers vs pointer receivers.
- Concurrent programming with Goroutines and channels.
- Simple network programming over TCP.
- Simple Web programming using the net/http standard package.
- Go build tools. Go modules.
If you are just starting to learn programming, then learn Go. Learn programming with Go. The Art of Go - Basics will guide you through your first steps in the wonderful world of programming!
Get this book now and start learning Go programming today!
Read more from Harry Yoon
A Hitchhiker's Guide to the Modern Programming Languages Einstein's Relativity: The Special Theory and the General Theory - Free Chapter 2 Rating: 0 out of 5 stars0 ratingsEinstein's Relativity: The Special Theory and the General Theory - Free Chapter 1 Rating: 0 out of 5 stars0 ratingsEinstein's Seven Essays on Relativity, Geometry, and Scientific Methods Rating: 0 out of 5 stars0 ratingsEinstein's Relativity Part I - The Special Theory of Relativity Rating: 0 out of 5 stars0 ratingsEinstein's Relativity: The Special Theory and the General Theory - Free Chapter 3 Rating: 0 out of 5 stars0 ratings
Related to The Art of Go - Basics
Related ebooks
The Way to Go: A Thorough Introduction to the Go Programming Language Rating: 3 out of 5 stars3/5Learning Go Programming: Build ScalableNext-Gen Web Application using Golang (English Edition) Rating: 0 out of 5 stars0 ratingsGolang Mini Reference: A Hitchhiker's Guide to the Modern Programming Languages, #1 Rating: 0 out of 5 stars0 ratingsMastering Go: Navigating the World of Concurrent Programming Rating: 0 out of 5 stars0 ratingsNode.js Design Patterns - Second Edition Rating: 4 out of 5 stars4/5Data Structures and Algorithms with Go: Create efficient solutions and optimize your Go coding skills (English Edition) Rating: 0 out of 5 stars0 ratingsData Structures and Algorithm Analysis in Java, Third Edition Rating: 4 out of 5 stars4/5Mastering Go Programming: From Basics to Expert Proficiency Rating: 0 out of 5 stars0 ratingsJavaScript Enlightenment Rating: 4 out of 5 stars4/5The Go Workshop: Learn to write clean, efficient code and build high-performance applications with Go Rating: 0 out of 5 stars0 ratingsGet Programming with Go Rating: 5 out of 5 stars5/5Learning Go Programming Rating: 5 out of 5 stars5/5Go Cookbook Rating: 5 out of 5 stars5/5Go Programming Blueprints Rating: 0 out of 5 stars0 ratingsBuilding Server-side and Microservices with Go: Building Modern Backends and Microservices Using Go, Docker and Kubernetes Rating: 0 out of 5 stars0 ratingsRust In Practice Rating: 0 out of 5 stars0 ratingsLisp Interpreter in Rust Rating: 1 out of 5 stars1/5Modern Web Development with Go: Build real-world, fast, efficient and scalable web server apps using Go programming language Rating: 0 out of 5 stars0 ratingsGo Design Patterns Rating: 5 out of 5 stars5/5Learn Rust Programming: Safe Code, Supports Low Level and Embedded Systems Programming with a Strong Ecosystem (English Edition) Rating: 0 out of 5 stars0 ratingsRESTful API Design - Best Practices in API Design with REST: API-University Series, #3 Rating: 5 out of 5 stars5/5PHP Error Reporting: How To Do It Right Rating: 0 out of 5 stars0 ratingsGetting Started with LLVM Core Libraries Rating: 0 out of 5 stars0 ratingsRust In Practice: A Programmers Guide to Build Rust Programs, Test Applications and Create Cargo Packages Rating: 0 out of 5 stars0 ratingsGo Programming Blueprints - Second Edition Rating: 4 out of 5 stars4/5PHP Microservices Rating: 3 out of 5 stars3/5Mastering Git Rating: 0 out of 5 stars0 ratings
Programming For You
Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5PYTHON PROGRAMMING Rating: 4 out of 5 stars4/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5Python for Data Science For Dummies Rating: 0 out of 5 stars0 ratingsPython Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Microsoft Azure For Dummies Rating: 0 out of 5 stars0 ratingsLearn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5Python Data Structures and Algorithms Rating: 5 out of 5 stars5/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5Learn SQL in 24 Hours Rating: 5 out of 5 stars5/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5Beginning Programming with C++ For Dummies Rating: 4 out of 5 stars4/5Algorithms For Dummies Rating: 4 out of 5 stars4/5Beginning Programming with Python For Dummies Rating: 3 out of 5 stars3/5
Reviews for The Art of Go - Basics
0 ratings0 reviews
Book preview
The Art of Go - Basics - Harry Yoon
I: First Steps
A journey of a thousand miles begins with a single step.
The code examples in this book are meant to be read. You do not have to type them on computer to get hands-on
experience.
1. The Simplest Go Program
1.1. Agenda
We will review our first Go program together.
Smallest Program1.2. Code Reading
Here’s a small Go program.
Listing 1. smallest-program/main.go
The label indicates that the source code is copied from a file main.go under a folder named smallest-program.
The line numbers, printed on the left-hand side, are not part of the program. They are included for easy reference.
1.2.1. Explanation
This is the simplest Go program that compiles and runs, in a single file (named main.go
in this example). It does nothing.
You can run this program as follows on command line.
1.2.2. Keywords
This simple program includes two Go language keywords
.
A keyword in a programming language is a word or identifier that has special meaning to the language and the language tools such as compilers. Programmers cannot use language keywords for other purposes, e.g., as variable names, etc.
Go comprises 25 keywords. This example program uses the following two:
package: The package line is a declaration indicating that this source file belongs to a certain package, main in this example.
func: The keyword func declares a function and introduces its definition to the program. main() is a special function, and the func declaration has a slightly different semantics.
The book gradually introduces important concepts through repetitions. You do not have to try to understand everything in your first encounter, especially if you are new to programming. Remember, knowledge is mostly about familiarity.
1.2.3. Grammar
A Go program is written in one or more source files. Each source file must start with the package line. This is called a package declaration
.
A package is a basic unit of organization in the Go language. In many programming languages, a file is typically a basic unit. In Go, however, it is the package, which can include one or more files.
An executable Go program has to include a special package main
, as in this example.
A go program comprises a set of packages. Each package can include a certain top level declarations, and most importantly, function definitions. Functions are essential components of Go programs. We will get back to the topic of functions in later lessons.
Empty lines, such as the second line of this example code, are ignored by the compiler.
1.2.4. Deep Dive
In some program languages, an empty program is a perfectly valid one. In Go, however, an empty program (or, an empty source code file) does not exist.
Every runnable program has to include at least one (and no more than one) main function, which should be part of the main package.
If you run the above program, then you’ll see the following output:
That is, nothing. The fact that the program runs and does not produce an output does not necessarily mean that the program has done nothing. But, in this case, the program itself does literally nothing.
A Go program can be clearly more complex than this simple example. A program can include many lines of code and it can include a large number of packages and source files, etc. But, there is one commonality across all different Go programs, from the simple to the most complex.
Each Go program starts running from the main function. The definition of a function, e.g., a set of statements to be run, is to be included inside a pair of curly braces, {…}.
In this example, the main function just happens to be empty. We can clearly see that there is nothing between the opening and closing curly braces in the source code. This means that we are telling the computer to do nothing. And, it will do nothing, if it runs successfully (other than the basic work done by the operating system to load the program into memory, etc.).
1.3. Summary
We introduced the important concepts of packages and functions in this lesson. They will be discussed in more detail in later lessons.
1.4. Questions
What is the first line of a Go program source file?
What is a main() function?
Author’s Note
Development Environment Setup
We are not going to discuss how to install Go tools in this book. That is a trivial
(albeit important) task, which you can figure out using various resources (e.g., Web search).
Having a Go development environment on your computer is not a prerequisite to reading this book.
If you haven’t installed the Go tools, and if you would like to do so, then there is a quick instruction on the golang website: golang.org/doc/install.
You can also use the online Go Playground to try out simple code.
Most of the sample code in Part I that fits, or can fit, into a single source file can be run on the Playground.
There are many different types of resources that can help you learn programming in Go. The Art of Go - Basics: Introduction to Programming in Go for Smart Beginners is designed to be read. This book is not meant to be used as a stand-alone be-all and end-all book.
What is Programming?
This section is for readers who have never done programming before. You can skip this section if you have some (hands-on) experience with programming.
If you are completely new to coding, then it can be rather daunting. You may not be sure what we are doing here.
A program is essentially a series of instructions that a computer is to read and execute. The problem is that computers do not understand human languages like English.
We use specially created programming languages, like Go, to write programs. Computers, however, do not understand any of these programming languages either. We will have to go through a certain process to convert a program written in one of these high-level
programming languages to an instruction set in the language that a particular computer understands, which is essentially in 0's and 1's.
This process, or at least the most important part of this process, is known as compilation. The details of this process varies from language/runtime to language/runtime.
Now, focusing mostly on the Go programming language, the Go compiler toolchain converts a program
(e.g., a set of source code files, as we will discuss in more detail in the coming lessons) into an executable for a particular computer architecture.
By default, the executable is generated for the architecture of the computer where the build is done. But, you can also cross build
, that is, you can build executables for different target architectures.
This is one of the most interesting things about Go. Other high level programming languages comparable to Go such as Java or Python compile the source program into byte code
or intermediate code
, not directly to the machine code. These byte code run on a virtual machine, or an intermediate language runtime or interpreter.
Go does not have such virtual machines or runtimes. Go code is always compiled to an executable of a target architecture(s).
The Go runtime
is embedded/linked into each executable/binary. The Go runtime includes a garbage collector
.
When a program runs, it uses/consumes various host computer resources such as memory. Some of the allocated memory may have to be cleaned, while the program is running, because they are no longer used. Otherwise, the program may run out of usable memory space. This is especially important for long running programs. The Go runtime periodically checks the memory and cleans up the space. This is called garbage collection.
To sum, a programmer creates a program, a set of source files, which is written in the Go programming language. The programmer then compiles/builds, or converts the source program into a binary/executable for a target computer architecture. The executable, or the program
, generated this way can be distributed and installed
on other computers with the same architecture.
Programming
may broadly refer to this whole process of creating an executable(s). Or, more typically, programming refers to a process of writing these source code, which are to perform a certain desired task, when compiled and built into a machine code.
A program may include various instructions (or, statements
). It may include conditional statements and repetitions, or loops
, among other things.
Programmers use various tools to do programming. For example, they may use text editors or IDEs (integrated development environment). They also need to use certain tools, e.g., compilers
, that convert the given set of source files into a binary. When programming in Go, we use a suite of command line tools, go
, that provide such functionalities. For example, we use go build to compile/build a Go source program.
We will look into these concepts in more detail throughout this book.
2. Hello World 1
2.1. Agenda
We will review a few simple Go programs which do basic input and output in this and the following few lessons.
Hello World 12.2. Code Reading
Here’s a simple hello world
program in Go:
Listing 2. hello-world-1/main.go
Throughout this book, the label of a source code snippet indicates that the example code is taken from a certain file in a certain folder (on the author’s computer). The source file names, and the file paths, are largely irrelevant to the execution of a Go program.
2.2.1. Explanation
This program is not much more complicated than the one from Lesson 1. The code includes essentially one more line (excluding braces), println(…). The println() function prints out its argument to the console output.
We can run this program as follows:
It produces the following output:
2.2.2. Keywords
This hello world
example code in Go includes the following two keywords:
package: The package keyword declares a package that this source file belongs to, main in this particular example.
func: The func keyword generally declares a function and introduces its name and definition into the program. The main() function is special in a Go program, and any executable program should include one and only one main() function.
As stated, there will be (deliberately) a fair amount of repetitions across different lessons. You can skip any part of the book (not just the keyword sections) which you are already familiar with. As for the keywords, there is an appendix that includes all Go keywords, Go Language Keywords, at the end of the book.
2.2.3. Built-in Functions
println() (with a lowercase p) is a built-in
function.
It takes one or more string arguments (e.g., hello world!
), and it prints out the arguments to stdout (e.g., the console or terminal output). A newline is automatically added after the argument is printed (as the suffix ln indicates).
The Go programming language includes a few built-in functions which you can use in your programs without having to refer to any particular libraries.
Builtin functions may be considered more important
or more essential
in writing a program. The println() function is, however, an exception. There are better
functions in other libraries that do what println() does, and more. This built-in function may be deprecated or removed in the future releases of Go (although unlikely).
This is the only lesson in which we use println() in this book.
2.2.4. Grammar
A Go program is organized into one or more packages. A package in Go is a fundamental building block, which plays an essential role in many different aspects of the language.
A package can be written in one or more source code files. Each source file must start with the package declaration (excluding white spaces and comments):
This statement means that this source file (in which this source code is written) belongs to the named package.
In this example, the package name happens to be a special word main
, indicating that this source code file is part of the special main package of this program. Any executable Go program must include one, and only one, main package.
A package can include zero or more function definitions, among other things. A runnable Go program must include a special main() function as part of the main package. When the program is executed, the operating system invokes the main() function of the Go program as an entry point. The main function has the following syntax:
The middle line is a program comment, which is included here for illustration. Comments are (mostly) ignored by the compiler. If you are new to programming, the important part of this syntax is the keyword func, main, (), {, and }, in this particular order.
The body of a function, from right after the opening bracket {
to just before the closing bracket }
, can include any number of statements. A statement
in a program is an instruction to the computer as to what needs to be done.
The main function of the example program above includes one statement (one more than the first example),
It is a function call
. This statement is an instruction to call a function
, the builtin println() function in this example, with an argument hello world!
.
The text hello world!
(including the opening and closing double quotes ) is an example of a string literal
.
As stated, we will briefly introduce certain concepts or topics in earlier lessons and elaborate on them later in the subsequent lessons. Many of the explanations given in this book, especially those in the earlier lessons, are, by necessity, incomplete.
2.2.5. Deep Dive
In some programming languages, it requires only one line of code to print hello world
(or something similar) to the console.
In Go, it requires 4 or 5 lines (depending on how you define a line
). Different programming languages have different tradeoffs in their language designs.
A Go program starts when the system calls the main function. The Go program executes the statements in a function from top to bottom, more or less. (Not all of them may end up being executed, however.) When a function has no more statements to run, the function returns. When the main function of a program has no more statements to run, the program exits.
In this example, the program has only one function, the main() function, and the function includes only one statement println(hello world!
), which is a function call.
When the println() function does its job (i.e., printing hello world!
to the standard output), it returns to the caller, which is the main() function. Since there is no more statement after println(), the program terminates.
Author’s Note
Why Hello World?
Doing Hello World
is now almost a rite of passage for beginning programmers.
So, why do we do it? One of the important roles which this type of simple programs play is, in fact, to verify your development environment setup.
Suppose that you have just installed the go tools from the golang.org website. How do you know that they work
? How do you know that your installation was successful? A quick way to test the dev env setup, including the build tools, is to test the build system using a simple program.
That’s where the Hello-World program comes in. When you install the Go tools (if you haven’t already done so), try to build and run your hello world program, and make sure that it compiles and runs.
This is like a chicken-and-egg problem.
If you don’t have the tools, you cannot create a program. If you don’t have a program, you cannot test the tools.
3. Hello World 2
3.1. Agenda
We will review another simple Go program in this lesson.
Hello World 23.2. Code Reading
Here’s a slightly more complicated version of the hello world
program.
Listing 3. hello-world-2/main.go
This source code file has the same name main.go
, but it is stored in a different directory, hello-world-2
.
The file name main.go
has no special significance. A source file that includes the main function of the program is typically, but not always, named main.go
.
3.2.1. Explanation
This example program includes a bit more components, and a few more lines of code. You can run the program as before:
It produces the following output:
3.2.2. Keywords
This program includes three new keywords:
import: import declares that the source file depends on the functionality of the imported package, which is specified by an identifier for finding and accessing the package.
const: const declares a list of constant names. The const declaration binds those names to the values of a list of constant expressions. The number of identifiers must be equal to the number of expressions.
var: var declares one or more variables. The var declaration binds the given identifiers to those variables, and gives each a type and an initial value.
3.2.3. Grammar
In Go, packages serve as basic components for code sharing. If you know how to find a package anywhere on the Internet, and if you have permission to access the source code of the package, then you can use it in your program, or more precisely in your package.
In many programming languages, code reuse is often based on special constructs like libraries
(e.g., C/C++, …) or packages
(e.g., Node.js, Python, DotNet, … not to be confused with Go packages), or just simple archive files like jars
or wars
(e.g., Java).
In Go, no special packaging
is needed. If you know how to access the source code of a package, then you can use it.
Likewise, if anybody knows where you keep your source code (of a certain package), and if they have a permission to do so, then they can use your code (of that package).
We will discuss this code sharing aspect of packages further throughout the book, but one thing to note here is that you cannot share your main packages. The sole purpose of the main package, along with the main function, in a program is to make the program executable. The main packages cannot be shared with other Go programs.
Go comes with a set of special packages known as the standard library
(just like any other programming language). The fmt
package is one of them. And, the import fmt
statement of the example code lets you use the fmt package in your code.
The Go language specification does not specify, or dictate, how exactly you specify the location of somebody else’s packages.
In the case of the standard libraries, you simply use the name of the package in the import declaration. The go compiler knows where to find them.
The pair of double quotes around the package name is part of the syntax.
Once you import
an package into your program, you can use the imported package just like it is a part of your own program. (We will cover the access control aspect of a package in later lessons.)
The import statement introduces the names, such as those of functions or other declarations, in the package into your program so that you can use them.
Line 9 of the hello-world-2
example shows how to use Println() function from the fmt
package. You just use the imported package name as a prefix with a dot, .
.
The fmt package’s Println() (with a capital P) is very similar to the builtin println() function. It prints out its string arguments to stdout.
In the example code, the argument happens to be an expression
, greeting +
+ name.
An expression is a fancy term for a value
(as the compiler sees it) or anything that evaluates to a value. Hello!
(a string literal) is a value, and hence it is an expression. A number 5 is an expression as well as 2 + 3 since it evaluates to 5, which is a value.
In this example, the argument of the Println() function is a string concatenation (denoted by +
), which evaluates to a value, i.e., another string. For example, hello
+ world
is helloworld
.
The expression, greeting +
+ name, includes two other Go programming constructs. Namely, constants
and variables
.
In this case, the name greeting is a variable, as declared by the var keyword in line 8.
And, the name, name, is a constant, as declared by the const keyword in line 5.
Both declarations have more or less the same syntactic structure.
There is an equal sign = in the middle. On its left hand side, there is the keyword var or const followed by a name, or an identifier
, and a type
, string in this case. Note that, in some languages, the type comes before the identifier, and in other languages, the order is reversed.
On the right hand side of =, there is an expression, string literals in both cases.
In this particular example, const and var declarations are placed in different places, one inside a function (the main() function in this case) and the other outside a function. But, that is just incidental.
Both const and var declarations can be used within a function or outside. Their placement affects the constant/variable’s scope
. Scoping
is a big topic, and we will cover scoping throughout this book.
The difference between const and var is that const can declare names which do not change during the execution of a program. In fact, the value of a const name should be known at compile time. The right hand side of the const declaration should be a constant expression
.
On the other hand, the value of a var name can change. One can assign
a different value, or it can change as a result of other operations.
Go is a statically typed language. All consts and vars have specific types, known to the compiler, at compile time (there are exceptions), and their types do not change during the execution of a program.
Clearly, type is a very big, and important, subject, and we will have to defer its full coverage to later lessons.
Just to give a quick explanation, however, a type defines what a const/var is, how to interpret its values in memory, and what kind of values the const/var is allowed to have, among other things.
Not to repeat the same points, but whatever doesn’t make sense to you at this point, you can just ignore and move on. You can always come back later, if necessary.
3.2.4. APIs
Being familiar with common libraries, especially the standard libraries, is an important part of becoming a proficient programmer in a given programming language.
Although it is not a main focus of this book, we will try to touch as many standard library functions and types as possible, and we will document some of them in these special sections, APIs
.
In the example hello-world-2
, we use package fmt
, and one of its exported functions, Println().
Package fmt: Package fmt implements formatted I/O with functions analogous to C’s printf and scanf. The format verbs
are derived from C’s but are simpler.
func Println: Println formats using the default formats for its operands and writes to standard output. Spaces are always added between operands and a newline is appended.
This information is taken from the official Go documentation pages.
3.2.5. Deep Dive
The example code, however simple it may be, illustrates one of the most important structures in a Go program.
A Go source file follows this structure:
package declaration (line 1),
one or more import declarations (line 3), if needed, and
the rest
(lines 5~10).
Every Go source file has to follow this structure, in this particular order.
We have not fully explained what you can put in the rest
part. But, we have seen some examples like function definitions. You cannot put arbitrary statements like fmt.Println(…) here. Many of the general kind statements are only allowed inside a function definition.
Other types of statements that can be put at the top-level, or in the package scope
, include const and var declarations, as demonstrated by the example code.
As indicated, both kinds of declarations could have been put in the package-level scope. Or, both inside the main() function (function scope
).
A name can be used only within a valid scope, that is, (typically) within a block where the name is introduced, including its inner blocks, if any. In case of a const/var, its scope starts from the point where the name is first introduced and it ends at the point where the enclosing block ends. The package scope
is a little bit different from other scopes (e.g., functions, blocks), but essentially the same rules apply. Any name that is included outside a function in a source file is in the package scope (which includes all source files within the same package).
As an example, the following code will be valid. The const name can be used within the main() function, or outside.
On the other hand, the variable greeting is in the main function’s function scope. After the closing bracket } of the function, it cannot be used. In fact, this variable cannot be used before the declaration even within the same block. In this small example, there is nothing else before the declaration (line 8), but even if there were any statements, they could not have used greeting. In case of variables, the scope
starts from the line where the variable is declared.
All C-style programming languages have more or less the same scoping rules.
In Javascript, if you have used Javascript before, one can declare variables in two different ways, using var and let. (Or, one can just declare variables globally, which is not generally recommended.) Variables declared with let follows the same scoping rule, whereas those declared with var have slightly different scopes. They can be used even before their declarations. Their values are undefined if they are accessed before their declarations.
In Go, trying to use a const/var before its declaration will cause a compile time error.
Note also that we could have used either const or var for both name and greeting, in this particular example.
As a program gets larger and more complex, the choice of const vs var, and their scope, will be important. As a general rule, it is a good practice to prefer constants to variables whenever it makes sense. It is also a good practice to declare consts/vars within the smallest possible scope.
In this particular example of hello-world-2
, both names should have been const and both should have been declared within the main() function before we use them (e.g. before fmt.Println()).
But, choice of const and var also conveys certain information (to the compiler as well as to the human readers).
For example, suppose that your name happens to be Joe
. This fact will not change even if the program grows bigger and if the program ends up including more functions, etc. Putting the name name in a package scope as const would make more sense in that case.
On the other hand, suppose that your intention was trying out different greeting phrases within the program. In such a case, it would make sense to make greeting a variable. We could assign a different value to it, if needed.
For example,
Many of the code snippets we use in this book may not be a complete program, as in this example. This should be obvious from the context or from other cues. For instance, this code snippet does not follow the general structure of a Go source file, and hence it cannot be a complete program, or even a package.
①
is the now-familiar var declaration.
②
the Println() will print out Hello Joe!
③
is an assignment
statement. The assignment changes the value of the variable.
④
the output will now be Hi Joe!.
The first line of the code snippet declares a variable, greeting, and it initializes its value to Hello
. One can also just declare a variable first and assign a value later in two different statements.
If a var is declared without an explicit initial value, then the type’s default value
, or zero value
, is automatically assigned. In the case of the string type, the default initial value is an empty string ().
When a const/var is declared with an initial value, as in our lesson example, the compiler may be able to easily infer the type of the constant/variable. In that case, the type specification in a const/const declaration may be omitted.
For example,
The type of the variable greeting can be easily inferred, say, based on the type of the expression/value on the right hand side, i.e., a string literal in this example. Hence the variable greeting is of type string. This is called type inference
, and the type is normally omitted in const/var declarations unless necessary.
In the example program, the fmt.Println() function takes a single argument, which is a string concatenation of three strings. We could have