Go Basic Syntax Tutorial

In this Go tutorial we learn some basic syntax of programming in Go.

We learn about tokens, how statements are terminated, comments, identifiers, curly braces and scope, keywords and operands.

Tokens

Code in Go is made up of tokens. A token is a keyword, a name (identifier), symbol, operator, string etc.

As an example, let’s consider a simple statement that prints the text ‘Hello World!’ to the console.

Example:
 fmt.Println("Hello, World!")

The individual tokens would be:

Example:
fmt
.
Println
(
   "Hello, World!"
)

Line breaks

In Go a line break symbolizes the end, or termination, of a statement.

Example:
fmt.Println("Hello, World!")
fmt.Println("I'm learning Go")

In the example above, the two lines of code are considered two separate statements by the compiler.

Technically, Go uses semicolons ( ; ) to terminate statements but it’s not typically written in the source code, it’s automatically added by the compiler later on.

That said, the code won’t break if you add semicolons explicitly.

Example:
package main

import "fmt"

func main() {

    fmt.Println("Hello, World!");
}

Comments

Comments are a way for us to document our code and enhance its readability. Comments in Go are ignored by the compiler, which means the compiler won’t try to execute any text or code written inside a comment.

In most cases, we shouldn’t need comments, our code should be written cleanly and clearly enough so that it’s obvious as to what the code does. That said, there are many situations where we should make use of comments.

  • When learning programming, or a new language, it’s helpful to comment our understanding of the code.
  • When working on large projects as part of a group, we should provide comments so that others immediately understand what’s going on.
  • When using external libraries it may be useful to include short comments so it’s not neccesary to visit the library’s documentation that often.
  • When we’re working with complex code it may not be immediatly clear what the code is supposed to do. Commenting would make it easier if we need to come back to the code at a later time.
  • When we’re debugging/testing. We may want to temporarily remove pieces of code from execution by commenting them out.

Go supports both block comments and C++ style single line comments.

Block comments consist of an open tag and a close tag.

Syntax: block comment
/*
    Anything between the open and
    close tags is a comment even
    if they span multiple lines
*/

C++ style line comments are prefixed with two slashes and is only used on a single line.

Syntax:
 // This is a single line comment

Most programmers prefer to use single line comments, even if they write multiple lines.

Example:
// Maybe it's because it's simply
// faster, but most devs like to
// use line comments instead of
// comment blocks

Identifiers (names)

An identifier is the name we use to identify things like variables, functions etc. There are a few rules and conventions when it comes to naming our identifiers, let’s go through some of them now.

1. A name cannot start with a numerical value, but may contain a number inside of it.

Example:
// Not allowed
21_Jump_Street

// Allowed
mambo_number_5

2. A name may start with uppercase or lowercase alphabetical letters (A - Z or a - z), and underscores ( _ ).

Example:
// Allowed
Name
name
_name

3. A name may not contain special characters such as $, @, % etc.

Example:
// Not allowed
^_^
usern@ame
#lostsock#thestruggleisreal

4. Most names are case sensitive, which means that a name with lowercase letters is not the same as a name with uppercase letters.

Example:
// Not the same
learning
LearNing
LEARNING

5. A name should not contain a Go specific keyword. Keywords are words that are reserved by Go for special uses.

Example:
if
map
import

The convention in Go is to use either PascalCase or camelCase to name identifiers.

When using pascal case, the first letter of a word is uppercase. If the name has multiple words, each new word is directly connected to the previous word but the first letter is also uppercase.

Example:
// Pascal case
Name
FirstName

When using camel case, the first word of a name is lowercase. If a name has multiple words, each new word is directly connected to the previous word but the first letter is uppercase.

Example:
// Camel case
name
firstName

The convention for constants in Go is different. Constants are usually written in only uppercase and words are separated with underscores.

Example:
// Constants
FIRST_NAME

Characters

A character, or char, is a single letter of the alphabet and is always wrapped in a pair of single quotes.

Example:
 'a'

If we try to type more than one letter between single quotes, the compiler will raise a ‘invalid character literal’ error.

Strings

A string is an array of characters combined to form words or sentences. Strings are always wrapped in double quotes.

Example:
 "Hello, World!"

We can use single quotes inside strings where we need them.

Example:
 "I don't like debugging"

Scope

Go uses open and close curly braces to define local scope. Everything inside the curly braces is of that scope.

Example:
func main() {

   var msg = "Hello, World!"
}

In the example above, the variable msg is between the main() function’s curly braces.

The variable is in the function’s local scope, it belongs to the main() function and cannot be used outside of the curly braces.

If a variable is defined outside of the main() function, it will be of a global scope, which means that it can be used by any function in that script.

Brace wars

Typically, in other languages that use curly braces to define scope, we’re allowed to place the opening brace on its own line.

In Go we can’t do that because semicolons are inserted by the Go compiler as it scans the code and writing the brace on its own line will break the code.

Example:
// Correct
func main() {

   var msg = "Hello, World!"
}

// Incorrect
func main()
{
   var msg = "Hello, World!"
}

Keywords

Keywords are reserved words that have a special meaning to Go compiler.

The following keywords are available to us in Go:

breakcasechanconstcontinue
defaultdeferelsefallthroughfor
funcgoGotoifimport
interfacemappackagerangereturn
selectstructswitchtypevar

We’ll use most of these keywords throughout the tutorial course.

Operands, lvalues and rvalues

There are two kinds of expressions in Go, lvalues and rvalues. The operand on the left side of the assignment operator ( = ) is the Lvalue, and the operand on the right side is the Rvalue.

Lvalue:

An Lvalue can have a value assigned to it so it’s allowed to appear either on the left or the right side of an assignment.

Example: lvalue
// lvalue (msg1) may be on the left
num1 = 10

// or on the right of the =
num2 = num1

Rvalue:

An rvalue cannot have a value assigned to it so it may only appear on the right side of an assignment.

Example:
// rvalue (10) may only be on the right
num1 = 10

// and cannot be on the left
10 = 10

Summary: Points to remember

  • We use line breaks to terminate statements in Go
    • Code will still compile if a semicolon is used
  • Go supports block comments with open and close tags or line comments with double slashes
  • Identifiers are the names we give our variables, constants, functions etc.
  • Anything written in between curly braces becomes local to that scope.
  • The opening curly brace in a statement may not be written on its own line.
  • Keywords are reserved words that have special meaning to the compiler.
  • Go has two kinds of expressions, lvalues and rvalues.
    • lvalues may be on both the left and right of the assignment.
    • rvalues may only be on the right of the assignment.