DEV Community

Cover image for Deep dive into Go syntax and types
Azeez Lukman
Azeez Lukman

Posted on

Deep dive into Go syntax and types

The syntax of a programming language is the set of rules that defines the combinations of symbols that are considered to be correctly structured statements or expressions in that language.

Go syntax is the set of rules that defines how a Go program will be written and interpreted by both the runtime system and by human readers. In this article, we would dive into the patterns for writing a valid Go program.

Design philosophy

Go is a programming language that focuses on simplicity and speed. It’s simpler than other languages, so it’s quicker to learn. And it lets you harness the power of today’s multicore computer processors, so your programs run faster. The goals for creating the Go programming language are

  • Fast compilation
  • Less cumbersome code
  • Unused memory freed automatically (garbage collection)
  • Easy-to-write software that does several operations simultaneously (concurrency)
  • Good support for processors with multiple

Keywords

Go has 25 reserved keywords. The following list shows the reserved words in Go. These reserved words cannot be used as constant or variable or any other identifier names.

case defer Go map struct
chan else Goto package switch
continue fallthrough if range type
chan for import return var

Whitespace

This term is used in Go to describe blanks, tabs, newline characters, and comments. A line containing only whitespace is known as a blank line.

Go compiler ignores whitespace

Whitespaces separate one part of a statement from another and enable the compiler to identify where elements in a statement, end and where the next element begins.

var name string;
Enter fullscreen mode Exit fullscreen mode

In this statement, the space character is the whitespace that enables the compiler to distinguish the var keyword from the name and from the string.

Tokens

A token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following Go statement consists of six tokens −

fmt.Println("Hello, World!")

Enter fullscreen mode Exit fullscreen mode

The individual tokens are −

fmt      // token 1
.      // token 2
Println        // token 3
(        // token 4
   "Hello, World!"    //token 5
)        // token 6
Enter fullscreen mode Exit fullscreen mode

String Literals

A string is a series of bytes that usually represent text characters. You can define strings directly within your code using string literals. String literals are text characters within quotation marks.

"Hello World"
Enter fullscreen mode Exit fullscreen mode

Including characters like newlines, tabs and some others that you can't include within the strings directly are represented by placing a backslash (' \ ') followed by the character. These are known as escape sequences.

"Hello, \nWorld" //places the following characters on a newline
//Hello,
//world
Enter fullscreen mode Exit fullscreen mode

Here are some of Go string literal escape sequences

\n New line character
\" Double quotation marks
\ Backslash
\t Tab

Runes

Go runes are used to represent single characters. String literals are surrounded by double quotes, but runes are surrounded by single quotes. The characters themselves are not stored but held as numeric codes.

Go uses the Unicode standard for storing runes. This allows for wide support for almost any language.

'A'  // returns 65
'B'  // returns 66
Enter fullscreen mode Exit fullscreen mode

The list goes on... runes also support escape sequences.

Types

Values in Go are all classified into different types, based on what the values can be used for. Integers can be used in math operations, but strings can’t. Strings can be capitalized, but numbers can't. every value has its own place.

Go is statically typed, which means that it knows what the types of your values are even before your program runs. So you are expected to use the proper type otherwise the compiler complains about that.

Functions expect their arguments to be of particular types, and their return values have types as well.

  • int: An integer. Holds whole numbers
  • float64: A floating-point number Holds numbers with a fractional part.
  • bool: A Boolean value. Can only be true or false.
  • string: A string. A series of data that usually represent text characters.
  • nil: A null value. Contains no value

The reflect package helps you find out what the type of a value is by passing the value into the package.

Numbers

Go treats integers and floating-point numbers as different types

Operators

Addition ( + )

3 + 2    //5
Enter fullscreen mode Exit fullscreen mode

Subtraction ( - )

3 - 2    //1
Enter fullscreen mode Exit fullscreen mode

Multiplication ( * )

3 + 2    //5
Enter fullscreen mode Exit fullscreen mode

Division ( / )

3 / 2    //4
Enter fullscreen mode Exit fullscreen mode

Comparisons

Go allows you to compare two or more values, the result of a comparison is a Boolean.

Using == checks for equality(if the values are equal). Using != checks if the values are not equal. Using < and > checks for the greater or lesser of two values. <= tests whether the second value is less than or equal to the first, and >= tests whether the second value is greater than or equal to the first.

4 == 4  //true
4 != 6  //true

4 > 6   //false
4 < 6   //true

4 >= 4  //true
4 >= 6  //true
Enter fullscreen mode Exit fullscreen mode

Variables

A variable is a piece of storage holding a value. The process of creating a variable is known as variable declaration. In Go, you can give declare a variable by using the var keyword followed by the desired name and the type of values the variable will hold.

var name string
var isDeveloper bool
Enter fullscreen mode Exit fullscreen mode

Once you declare a variable, you can assign any value of that type to it with =

name = "Lukman"
isDeveloper = true
Enter fullscreen mode Exit fullscreen mode

There is a quicker way to declare variables in Go. If you know beforehand what the variable's value would be, you can declare variables and assign values to them immediately

var name string = "Lukan"
var isDeveloper bool = true
Enter fullscreen mode Exit fullscreen mode

Usually, you can omit the variable type from the declaration if you assign a value to the variable at the same time as you declare it. The type of the variable would be inferred from the value assigned to the variable.

var name = "Lukman"      //declared as a string type
var isDeveloper = true   //declared as a bool type
Enter fullscreen mode Exit fullscreen mode

Short variable declarations

There is an even quicker way to declare variables in Go, if you know what the initial value of a variable is going to be as soon as you declare it, it’s more common to use a short variable declaration. Because of how easy it is to declare short variables, they’re used more often than regular declarations. You’ll still see both forms occasionally, though, so it’s important to be familiar with both.

name := "Lukman"
isDeveloper := bool
Enter fullscreen mode Exit fullscreen mode

A Go file consists of the following parts:

  • Package declaration
  • Import packages
  • Functions
  • Statements and expressions
package main            // the program belongs to the main package.
import ("fmt")          // import files included in the fmt package
                            // A blank line. Go ignores white space. Having white spaces in code makes it more readable
func main() {        // declares a function main        
  fmt.Println("Hello World!")   // function made available from the fmt package. Prints Hello World to the console
}
Enter fullscreen mode Exit fullscreen mode

Line Separator

In a Go program, the line separator key is a statement terminator. That is, individual statements don't need a special separator like “;” in C. The Go compiler internally places “;” as the statement terminator to indicate the end of one logical entity.

For example, take a look at the following statements −

fmt.Println("Hello, World!")
fmt.Println("I am in Go Programming World!")
Enter fullscreen mode Exit fullscreen mode

Comments

Comments start with /* and terminate with the characters in between */. They are helpful for leaving messages for other team members, such as describing the intended action. During compilation, the Go compiler totally ignores comments.

/* my first program in Go */

Enter fullscreen mode Exit fullscreen mode

You cannot have comments within comments and they do not occur within a string or character literals.

Function

A function is a group of one or more lines of code that you can call (run) from other places in your program. When a Go program is run, it looks for a function named and runs that first.

A function is declared with the func keyword followed by the function name and the parenthesis '( )'. the parameters are passed in within the parentheses. A function may or may not have parameters

and brackets, the code to be executed is within the brackets. The return keyword identifies what is returned after the function has been executed. You can return nil if there is nothing to be returned

func main() {       // The first function that gets run in the application

 name:= "Lukman"

 func printName(name) {          // printName prints the name paremeter to the console
    fmt.Println(name)
  return nil
 }  

}
Enter fullscreen mode Exit fullscreen mode

After declaring a function, it can be invoked by calling function name together the parameter within the parenthesis

func main() {       // The first function that gets run in the application

 name:= "Lukman"

 func printName(name) {          // printName prints the name paremeter to the console
    fmt.Println(name)
    return nil
 }

ptintName(name)            // invoves the function  by passing in the name value as parameter

}
Enter fullscreen mode Exit fullscreen mode

Package

Now you have learned some of the important syntax n creating a Go program but here's another important one. This is the starting point for all go programs.

A package is a collection of code with similar functionalities, as little as a package for greeting a user to one for calculating the distance to the moon. A package is identified with the package keyword.

package main        //The package name main, every program must have one
import "fmt"

func main() {       // The first function that gets run in the application

 name:= "Lukman"

}
Enter fullscreen mode Exit fullscreen mode

A package can import another package to use methods declared in that package within itself by using the import Keyword.

package main       

import "fmt"             //This makes methods in the fmt package available here

func main() {       

 name:= "Lukman"
 fmt.Println(name)         // prints Lukman to the console                 

} 
Enter fullscreen mode Exit fullscreen mode

Identifiers

Generally, identifiers are used for identification purposes. In Go, an identifier can be a variable name, function name, constant, statement labels, package name, or type.

package main        //main identifies the name of the package

func main() {       //main here identifies the name of the function

 name:= "Lukman"           //name identifies the name of a variable           

}
Enter fullscreen mode Exit fullscreen mode

Conclusion

With this deep dive into Go syntax and types, you're ready to take over the world. But before that, There’s only one way to learn to develop Go programs: write a lot of code. Keep coding and taking over the world is only a matter of time.

Thank you for reading, I'm Azeez Lukman and here's a developer's journey building something awesome every day. Please let's meet on Twitter, LinkedIn, GitHub and anywhere else @robogeeek95

Discussion (0)