Program Structure and Environment
Source files have ".go" extension.
Every file starts with a package namespace declaration. All ".go" files in the same directory must have the same package declaration and thus belong to the same package.
Program execution starts at the main() function in the main package. So, for the program to be executable ...
- there must be a
mainpackage. This is somewhat similar to Java where there must be aMain.javafile. In Java, the file itself must be named asMain.java, whereas in Go, only the package namespace must be calledmain, the directory name can be anything. - there must be one and only one file in that
mainpackage with amain()function. This is also similar to Java where there must be aMainclass (inMain.javafile) having a function with a specific signature (public static void main(String[] args)).
There is no such requirement for Python though we often use the if __name__ == "__main__": pattern.
If the program is not required to be executed on it's own, then there need not be a main package.
// 'package' statement namespaces this file.
// main package is compulsory for executable programs.
package main
import "fmt"
// main() function is the entry point of the program (not just this single file).
// 'main' package MUST have a function named main().
func main() {
fmt.Println("hello world")
}
Compile with go build file_name.go. Or else build and run with go run file_name.go.
Go needs semi-colons as the statement terminators as per grammar rules. But the lexer will auto-insert one if there is no ambiguity. Because of this, Go recommends that we avoid putting semi-colon on each line unless it is absolutely necessary. In fact, Go's own auto-formatting tool gofmt will remove unnecessary semi-colons. This post is interesting to read.
Because of this auto-inserting-semi-colon feature, there is a tricky side-effect to understand. The { on the same line at the end of the function definition above (func main() {) is not a style, it is a must. If it is omitted (for example, if we want to style it by entering the opening curly brace on the next line), Go will insert a semi-colon after main() and thus the next line's { doesn't have any meaning by itself and thus the program doesn't compile.
A function or variable can be imported from other packages only if it's name starts with a capital letter. Strange. Also, unlike Python, Go programs don't compile if we import a function and don't use it. But there is a workaround for it by placing an underscore in front of the imported function name.
Comments are more like Java. // and /* ...... */.
Basics
Variables and Constants
Variables can be declared in a few different ways ...
package main
// package scope
// When declaring in package scope, the keyword var is compulsory because
// any statement in package scope must start with a Go keyword.
// So months := 35 is invalid here.
var months int = 35
func main() {
// function scope of function 'main'
// the := shortcut works only in the function scope.
distanceInKm := 43.5 // infers the type as float
// multiple variables can also be initialised at once with := shortcut
name, knowEnglish, age := "Lakshmi", true, 38
// we can use var in function scope too
var years int = 35
// multiple variables can be declared in one line with var
var apples, oranges int // d and e get zero value of int type i.e., 0
var firstName, secondName string // f and g get zero value of string type i.e., ""
// multiple variables can be declared and optionally
// initialised at once like so ...
var (
person string = "Nani"
isMarried bool = true
isEmployed bool
)
}
As Go is UTF-8 compliant, variable names need not be in English only. They can be in any language. Only rule is it must start with either a letter or _ and then it can contain letters, digits and _.
The zero values are :
- 0 for a number type like
intandfloat - "" for
stringtype falseforbooltype- The special
nilfor other types (pointers, functions, interfaces, slices, channels and maps)
Constants can be declared just like variables, with a const keyword instead.
const a = 32 // := operator not allowed for const declarations
const b int = 64
const (
c = 32.5
d string = "Venu"
)
When we want to create some sort of Enum functioality, we can use the iota keyword and const declarations to create one.
const (
Sunday = iota
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
)
// iota auto assigns the numbers.
// iota also takes care when we later add another constant in between.
In Go, a scope can be created with { } brackets just like in Java and JavaScript. In Python, indented block creates a scope.
Core Types
- booleans :
bool. Can betrueandfalse. In Python, they areTrueandFalse. - integers :
uint8,uint16,uint32,uint64andint8,int16,int32andint64.byteis alias foruint8.runeis alias forint32. Also, there areuintandintwhich are platform dependent (32-bit or 64-bit). Important thing to note is thatintis a different type from either of theint32orint64types, even if the values are equal. If u need even bigger numbers thanuint32oruint64, then u can usemath/big. Also, one more thing to note is if we try to assign values above the maximum allowed for that type, then Go raises an "overflows" error. But, if we increment the number beyond the max allowed one in the code, then Go will not raise any error, instead, it silently wraps around from the smallest number side of that type. This is dangerous if not taken care. - floats :
float32andfloat64. - text :
string: Go strings are simple slices (arrays) of bytes. Nothing more than that. As Go needs to support more than one type of encoding (though the default preferred one is UTF-8), Go strings do not assume any encoding on their own. So, they are just sequence of raw bytes. This is similar to the setup in Python2. That's whylen()on a string variable gives only the number of raw bytes, not the number of characters.rune: It's character type that stores a single UTF-8 multi-byte character. To figure out the number of characters of a string variable, we need to make a slice ofrunetype from it, and then applylen()on that slice. Or else, we can userangeon the string variable, which iterates over the characters (of typerune) one by one.- the special
nil: In fact, it's not a type. It's a special value which represents empty value of empty type.
Literals
Literals are the way you provide values to a variable.
Go supports two types of string literals.
- raw-strings : enclosed in back-quotes (`). Even "\n" is also not interpreted as new line.
- interpreted strings : enclosed in double quotes
".
For rune type, the character is to be surrounded with single quotes. Ex. var a rune = 'H'. Any single character surrounded by single quotes is interpreted as rune type by Go.
Operators
Go does not have a separate operator for integer division unlike Python (//). The division operator, /, in Go acts much like that in Java and other statically typed languages. See ...
15 / 2 // acts like integer division, results in 7
15.0 / 2 // results in 7.5
15 / 2.0 // results in 7.5
15.0 / 2.0 // results in 7.5
Logical Operators : &&, || and !. These are just like those in Java and JavaScript. The equivalent ones in Python are and, or, and not.
Go has the familiar bit-wise operators (&, |, ^, << and >> ) as well.
Basic Printing
fmt.Println(), fmt.Print(), and fmt.Printf() are the simplest and widely used printing functions.
fmt.Print() adds a space between parameters and also a new line at the end.
fmt.Printf() takes format strings. It doesn't add any spaces between paramaters, or a newline at the end. A few common formatting patterns are ...
%d: decimal (base 10) number%s: string%T: type of the variable%v: any value (use when u don't know exact type)%+v: any value, but with extra information for special types (ex.structfields)%#v: same as%+vbut also prints the type of the variables for certain types.
Besides, there is also the S family of functions that includes fmt.Sprintln(), fmt.Sprint(), and fmt.Sprintf(), which are used for creating strings based on the given format and the F family of functions that includes fmt.Fprintln(), fmt.Fprint() and fmt.Fprintf(), which are used for writing to files using an io.Writer.
Pointers
Like other languages .... * operator dereferences a pointer (gives the value stored at the memory address pointed to by the pointer), & operator gives the memory address of a variable.
The zero value of a pointer type is nil. As Go allows nil pointers, i.e., pointers to values that do not exist, it is better to check for pointer != nil condition before trying to dereference a pointer, otherwise, it will result in run-time errors.
Pointers can be created in a few ways ...
var a *int: Here,ais declared as a pointer type (to integer values). But it's value isnil. No memory address is allocated yet. If you Printf it with#v, then you get something like(*int)(nil).var a = new(int)ora := new(int): A memory location is allotted to storeintvalues. The memory location is initialised with the default zero value of 0. If you Printf it with#v, then you get some memory location like(*int)(0xc00002c008).a := &b: Here,bmust already be declared (anyhow it must have been auto-initialised with the zero value). Some special structs allow creating pointers to them without even declaring them first. Ex.a := &time.Time{}.
Function arguments which are normal values (copies) are managed by Go (most of the times) in stacks. Whereas, function arguments which are pointers (pass by reference) are managed by Go in heap memory.
Memory in heaps is reclaimed by a complex Garbage collection process and thus managing memory in heaps is comparatively more CPU-intensive than that in stacks.