Lesson 2
Understanding Go Basics

In this lesson, we will look at the basic building blocks of Go, including tokens, statements, comments, and identifiers. You will use these building blocks to create the code for your Go programs.

UNDERSTANDING STATEMENTS AND TOKENS

A Go program is a series of statements. A Go statement is a series of tokens. In this context, a token refers to any meaningful object in a statement, including the following:

  • Keyword: A reserved word used for special Go functionality
  • Operators and punctuation: Symbols used to do mathematical operations and organize or perform special actions
  • Identifier: Token used to identify things such as storage locations or functions that perform actions
  • Literal: A specific value or number, such as 123 or “Hello, world”

We will look at each of these types of tokens in more detail in this and subsequent lessons. For now, consider the following statement from the Hello, World! example from the previous lesson:

package main

This statement includes two tokens: package and main. The token package is a keyword in Go. The token main is an identifier for the package. Another line from the Hello, World! example is included the following print statement:

fmt.Println("Hello, world!")

This statement includes the following tokens:

  • fmt: This is an identifier that tells Go what library to use.
  • .: The dot is a token that identifies a hierarchy. This tells Go that Println is part of fmt.
  • Println: This is a keyword that references a function.
  • (...): Parentheses are operators that enclose the literal that the program will print.
  • "...": Quotes are operators that enclose the text string for the literal.
  • Hello, world!: The literal that the Println function should display.

Each of these tokens is required for Go to understand the entire statement and understand how to interpret it.

STATEMENTS

As mentioned before, a program is a series of statements. There are a few things you need to know about statements. In Go, a statement must end in a semicolon or in one of the following tokens:

  • an identifier
  • an integer, floating-point, imaginary, rune, or string literal
  • one of the keywords break, continue, fallthrough, or return
  • an operator or punctuation, such as ++, --, ), ], or }

Some statements have additional rules that supersede those given here. For example, when you declare a variable, the var statement must include the data type for that variable to indicate what types of values can be stored. These additional rules will become clearer as you work through future lessons in this book.

It is worth looking at a few statements to see how they are presented. Each of the statements in the program presented in Listing 2.1 ends with an appropriate final token.

Given these rules for how statements must end, we would be able to change the fourth line to

var x

In this context, x is an identifier, and lines can end with identifiers. However, when we try to run the program, the compiler will produce an error (a syntax error to be more specific) because no type is specified for the variable:

.main.go:6:9: syntax error: unexpected newline, expecting type

In this case, the program doesn't know what type of information can be stored in x because we didn't tell it. Don't worry, in Lesson 3, “Storing with Variables,” you'll learn how to define types so that you can avoid this error.

Let's look at the Hello, World! program again. Many other programming languages use semicolons at the end of each statement to indicate the end. We originally wrote our Hello, World! program without semicolons. Listing 2.2 presents the Hello, World! program again.

Each of the statements in this program ends with an appropriate token from the list presented earlier. We could, however, rewrite the program to include the formal semicolons at the end of each line, as shown in Listing 2.3.

The formal semicolon makes it clear that the statement has ended. With Go, however, these semicolons are not needed.

You might wonder why we would want to include a semicolon at the end. We can use a semicolon if we want to write several statements on a single line. For example, the program in Listing 2.3 could be written as a single line of code with semicolons at the end of each statement, as shown in Listing 2.4.

Because of the limited width of this book, the code is shown here on two lines; however, in your editor you can enter this on a single line. Going forward in this book, we will typically use line breaks instead of semicolons because using one statement per line makes the code more readable.

COMMENTS

Comments allow developers to properly document their code. When added correctly, the compiler will ignore comments. Comments are useful to document the life cycle of code development (by including the developers' names, dates, copyright information, and similar information), as well as to explain specific code to other developers. The Go language supports two comment formats: single-line or block.

Single-line Comments

Single-line comments can be included by using // followed by a space and then the comment. The compiler will ignore all text to the right of the double slashes on that line of code. Listing 2.5 shows a single-line comment being used on a line by itself.

When you compile and run this listing, the line starting with // is ignored by the compiler and therefore has no actual impact on how your program runs. When using single-line statements, it is best to start a comment at the same indentation level as the statement that the comment refers to. As you can see in Listing 2.6, this helps with readability.

In addition to single-line comments, you can add a comment at the end of a statement. You've seen examples of this type of commenting in earlier listings, including Listing 2.1. Listing 2.7 shows another example.

In this listing, everything starting from the double slashes to the right on any given line is ignored by the compiler.

The purpose of comments should be to help document and explain the code. They should bring clarity for someone new to the code or for someone who hasn't seen it in a while. As such, too many in-line comments can make code harder to read or even difficult to see the code itself. If you use standard syntax and well-named variables, comments should be used only to explain things that the code itself does not.

Block or Multi-line Comments

If you have comments that span multiple lines, you can either use // in front of each line or use block comments enclosed between /* and */. The compiler will ignore all text between these block comment markers. Listing 2.8 includes a block comment at the beginning of the listing.

When this listing is compiled, everything presented in the first several lines starting with /* and ending with */ is ignored. Even if Go statements are placed within this area, they will be ignored.

IDENTIFIERS

Identifiers are tokens that identify things like functions, types, and variables. In many cases, we will use existing identifiers, like functions included in imported packages. In other cases, we will create our own functions and variables, using Go's naming rules.

The naming rules for identifiers in Go are that they must start with a letter or an underscore, followed by a series of letters, underscores, or numeric digits. The following are valid identifiers in Go:

  • Age
  • age_15
  • _age20

You can see how these identifiers are used by looking at Listing 2.9.

In this listing, three identifiers are being created and assigned values. These are Age, age_15, and _age20. They are assigned a value of 10, 15, and 20, respectively. The values are then printed by passing the identifier names to the Println function we've used before. If you enter and run this listing, you'll see the following output:

10
15
20

You should be careful to avoid using invalid identifiers. The following are examples of invalid identifiers:

  • 0_age
  • 1_age
  • #age
  • $age

Listing 2.10 presents a version of the Hello, World! program that will not run because of invalid identifiers. Enter the code and run it to determine which identifiers are named incorrectly.

This listing creates two variable identifiers, which are assigned values. These values are then passed to a Println function to display on the screen with a space between them. When you run the program, you will see errors similar to the following:

.TestScan.go:6:8: syntax error: unexpected ^, expecting name
.TestScan.go:7:8: syntax error: unexpected literal 2022, expecting name

Try to correct the problems with the identifiers and run the code again to verify it works. When the identifiers have been corrected, you should see the following output:

Hello world!   The year is 2022.

You should have found that the first identifier, ^output, started with an invalid symbol. You can simply remove the symbol to have it work. The second identifier, 2022, is invalid because it starts with a number. To be used as an identifier, it needs to start with an underscore or a letter. You'll need to change these on the line where they are defined and assigned a value, as well as change them in the Println statement.

Case

Go is case-sensitive, so it is important to be consistent when you create identifiers. As an example, Listing 2.11 will not compile because it does not use the proper casing for the fmt.Println function.

The compiler returns the following error:

  .main.go:7:4: cannot refer to unexported name fmt.println
  .main.go:7:4: undefined: fmt.println

This error is a result of using println instead of Println. If you capitalize the P in println and recompile the listing, it should work cleanly. Listing 2.12 illustrates that when creating identifiers, you must be consistent in the use of case. Because Go is case-sensitive, the names Year and year are not the same, as you can see by trying to compile and run Listing 2.12.

Run the code to identify and correct the errors. After making all corrections, verify that the program runs as expected. A corrected version of this listing is provided at the end of this lesson.

Naming Conventions

Per Go's standards, if an identifier includes two or more logical human words, the identifier should use PascalCase (with each word capitalized) or camelCase (where the first word is lowercase but additional words are uppercase), without the use of underscores to separate the words. All the following use standard naming conventions in Go:

FirstName
firstName
LastName
lastName
HomeAddress
homeAddress

Because Go is case-sensitive, we recommend that you choose one of these options and use it consistently throughout your code. The use of camelCase seems to be gaining popularity at this time. If you are working with a team of developers, the team should agree on naming conventions to be certain that everyone is following the same guidelines.

KEYWORDS

Keywords in Go language are reserved tokens that cannot be used as identifiers. The following list shows the keywords in Go language:

  • break
  • case
  • chan
  • const
  • continue
  • default
  • defer
  • else
  • fallthrough
  • for
  • func
  • go
  • goto
  • if
  • import
  • interface
  • map
  • package
  • range
  • return
  • select
  • struct
  • switch
  • type
  • var

Because these keywords have special meaning in Go, they cannot be used to name a variable or a function that you create. For example, you can't create a function or variable called select because the select function already exists as part of the Go language. As you work through this book, you will learn what these keywords do.

SUMMARY

This lesson was a quick overview of a few key topics important for programming in Go. This included a brief look at tokens, statements, comments, and identifiers. You will use these building blocks to create the code for your Go programs. Starting in the next lesson, you'll begin to apply these building blocks as you learn how to create variables for storing information.

EXERCISES

The following exercises are provided to allow you to experiment with the tools and concepts presented in this lesson. For each exercise, write a program that meets the specified requirements and verify that the program runs as expected. The exercises are:

Exercise 2.1: Fixing Problems

Each of the code blocks in Listing 2.13 through Listing 2.15 includes at least one error that will prevent it from running. Fix the errors and test to make sure the code runs as expected. Comments at the top of each block will tell you what the code should do.

Exercise 2.2: Making a Statement

Using the Hello, World! program presented in Listing 2.2 as a pattern, write a program that displays the following text. Each item should be presented in a complete sentence on a separate line:

  • Your name
  • Your hometown
  • Your favorite food

For example, the output of your program should look something like:

My name is Barbara Applegate.
I live in Augusta, Georgia.
My favorite food is apple pie.

Exercise 2.3: Go Is Fun!

Starting with the code provided in Listing 2.16, add to the code as needed to change the program so that it only outputs the text Go is fun! You should add necessary code, but you should not delete any of the existing code.

Exercise 2.4: Printing Without Repeating

Starting with what is provided in Listing 2.17, add the code needed to display the text that is presented in the quotation marks to output without reentering the text that is in the quotation marks. While you can add necessary code, you should not delete any of the existing code.

Exercise 2.5: Tagging Your Code

Review the programs in this lesson. You should enter these programs into your editor and save them. You should then tag each listing by adding comments with the following information above the package main statement for each listing:

  • Your name (single-line comment)
  • The current date (single-line comment)
  • A short description of the purpose of the program (multi-line comment)

Compile and run the program to ensure that there are no errors and that the comments do not appear in the output.

Solution: Listing 2.12

The following is the corrected version of Listing 2.12. Did you find all the case errors?

package main
 
import "fmt"
 
func main() {
   var mainGreeting string = "Hello world!"
   var Year string = "The year is 2022."
   fmt.Println(mainGreeting, " ", Year)
}
 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset