Hello World,
Today I am going to start a Golang tutorial series. I am an experienced Java Developer however my job required me to learn Golang so I will be documenting my learning journey in a structured format. In this series, we'll go from absolute basics to somewhat intermediate in Golang. This is the first place you should start if you have just heard of the name "Golang" but never got a chance to learn it.
Go: Pros & Cons
Suppose C++, Java & Python had a child, they named it Go and so it inherits features from each one of these languages. Here are some of them:
- C-like Syntax, therefore Concise & Clean
- Garbage Collection, therefore Memory Safety
- Package Model, therefore Faster Builds
- Statically Typed, therefore Type Safety
- Free & Open Source, therefore More Support
Here is What Go Lacks?
- No overloading of functions & operators
- No classes & inheritance
- No exception handling
- No support for pointer arithmetic
After reading these counter statements you might be wondering why would someone go with Go(pun intended), check this & this out and you will know why.
Let's "Go" to First Program
package main
import "fmt"
func main() {
fmt.Println("Hello World!");
}
Points to remember:
-
main
is the first function that gets executed, similar to any other programming language. -
fmt
is a format library in-built in Go, it's used for formatted printing & more. -
import
statement is used to import external libraries in Go, like Java. -
package
is used for modularisation of Go programs, like Java.
Go Run & Go Build
Now it's time to build & run the program we just wrote, for this purpose we need to make sure we have Go installed in our system, you can refer this to install Go in your system.
Building Go Programs
$ go build main.go
This command will build your Go program into system native executable named same as your program file name (main.go), you can run the executable directly by calling the executable (main).
$ go build -ldflags "-s -w" main.go
The ldflags stand for linker flags, it passes flags to underlying Go toolchain linker. The flags -s
& -w
will disable creation of symbol tables for the compiler and hence reduce down the size of the executable.
Running Go Programs
$ go run main.go
This command will first build your Go program in system temp location & run it to show the output, once the run is completed, the build is discarded. In other words, this will simply run your Go program.
How Does Go Work?
Go programs doesn't require a VM to run like how Java runs on JVM, Go compiles the program into native executables that are specific to the system therefore Go doesn't support platform independence. However the load falls on the developer to build executables for Windows, Linux & Darwin systems.
Basics
Any Go program consists of:
- Keywords
- Identifiers
- Data Types
- Constants
- Variables
- Operators
- Functions
Keywords
The following keywords are reserved and may not be used as identifiers.
break default func interface select
case defer go map struct
chan else goto package switch
const fallthrough if range type
continue for import return var
Identifiers
Identifiers name program entities such as variables and types.
- An identifier is a sequence of one or more letters and digits.
- The first character in an identifier must be a letter.
Some identifiers are predeclared.
Predeclared Identifiers:
Types:
bool byte complex64 complex128 error float32
float64 int int8 int16 int32 int64 rune
string uint uint8 uint16 uint32 uint64 uintptr
Constants:
true false iota
Zero value:
nil _
Functions:
append cap close complex copy delete imag len
make new panic print println real recover
Data Types
Primitives:
int, complex, float, bool, string
Structured:
struct, array, slice, map, channel
NOTE: We'll cover each data type in further tutorials.
Constants
The syntax to define a constant in Go is as follows:
const identifier type = value
Points to remember:
- Constants must be evaluated at compile time.
- The
type
is optional as compiler will guess the type based on value at compile time. - Applies only to primitive data types.
- Can be enumerated with
iota
identifier.
Examples:
const c1 = "this is a constant string." // type is optional
const c2 float32 = 5/6. // period(.) at the end tells compiler to do float arithmetic instead of integer arithmetic.
const billion = 1e9 // possible
const funcValue = funcThatReturnValue() // compile time error, why?
const(one, two = 1, 2) // can combine various constant initialisation into once
const ( // using iota for enumeration
zero = iota // 0
one // 1
two // 3
three // 4
)
Variables
The syntax to define a variable in Go is as follows:
var identifier type = value
Points to remember:
- If
value
is not supplied,type
is required. - If
type
is not supplied,value
is required. - Variables are always initialised to default values (0 or nil).
- Variables declared inside functions have local scope.
- Variables declared outside functions have global scope(package scope).
Examples:
var variable1 int // syntactically ok
var variable2 // missing value & type, compile time error
var value = 3.48 // ok, defaults to float64 type
var isSet bool = false // ok
var ( // can combine various variable declaration into once
radius int
isSet bool
name string
)
Operators:
Following is the list of operators & delimiters in Go:
- | + & * ^ / << /= <<= ++ =
% >> %= >>= -- ! &^ &^= += &= -= |= *= ^= && == != ( ) || < <-
> <= [ ] >= { } := , ; ... . :
Operator Precedence:
Precedence Operator
5 * / % << >> & &^
4 + - | ^
3 == != < <= > >=
2 &&
1 ||
Local Assignment Operator( := ):
The syntax for local assignment operator is as follows:
identifier := value
Points to remember:
- The local assignment operator ( := ) creates new variables and assign value.
- It doesn't need
type
details as the compiler does guess it for you. - Local assignment operator must be used inside functions.
Example:
func main() {
value := 50.5
isSet := false
x, y, z := 3, 56.5, "hello" // x = 3, y = 56.5, z = "hello"
}
This concludes the first part of this tutorial series. Check out the second part here where I talked about all primitive data types and string handling.
Top comments (8)
"Here is What Go Lacks" - I'd like to add a 5th point:
Go does not support Generics!
This makes it effectively impossible to write generic functions/methods that handle a collection of objects of any type/subtype, and is the kiss of death for an FP (functional programming) style approach to coding (map/filter/reduce and so on).
Essentially this means that with Go you're forced to code imperative loops, ad infinitum, till you see blue in the face ... a big drawback compared to a language like Rust.
I really hope they're going to address this in a future Go version. I mean, I do appreciate the ethos of "Go keeps it dead simple" (and IMO the learning curve of Rust is way too steep), but lack of support for Generics isn't about keeping things simple, rather it's dumbing down things way too much.
I'll add another
Yeah it's funny how cobbled together the language seems, and how poor the type system is, but it's still hugely popular because people get stuff done with it - you can't really argue with that ...
The above 3 points are valid concerns, but for me it's the lack of Generics that sticks out like a sore thumb.
(one big reason why Go is so popular are the intuitive and incredibly useful Go Routines - another reason is its well-conceived and well-executed Standard Lib)
TBH I've had my share of probelm with absence of generic in go too.
Oftentimes find myself cooy pasting another part of my code with same functionality but different type.
But go is simply too simple and too opinionated. Everybody's codestyle are roughly the same and it's super easy to pick up on go projects codebase than, say, JavaScript.
Exactly! You end up copy/pasting and rewriting loops endlessly, because there are no Generics.
I think it's a good thing that Go is simple, that's the philosophy of the language and they should stick to it. I've also looked at Rust, and it's brilliant but it is HARD.
But, they should REALLY consider adding generics to Go ... if they're allowed to add one and only one thing to the language, generics it should be.
I guess generics are on their way in Go. Check freecodecamp.org/news/generics-in-...
Yeah I heard they were working on it, great to see that it's coming!
This is great, keep posting.