Go Top
advertise here!!!

Library || READ MORE || DOWNLOAD PDF || QUESTION ANSWERS || HOME

  • SOME INTRO ABOUT GO PROGRAMMING LANGUAGE ↓

    Go is a general-purpose language designed with systems programming in mind.It was initially developed at Google in year 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. It is strongly and statically typed, provides inbuilt support for garbage collection and supports concurrent programming. Programs are constructed using packages, for efficient management of dependencies. Go programming implementations use a traditional compile and link model to generate executable binaries.

    Go is a recent language which sits neatly in the middle of the landscape, providing lots of good features and deliberately omitting many bad ones. It compiles fast, runs fast-ish, includes a runtime and garbage collection, has a simple static type system and dynamic interfaces, and an excellent standard library.

    Meanwhile, Go takes a strong position on features that can lead to confusion and bugs. It omits OOP idioms such as inheritance and polymorphism, in favor of composition and simple interfaces. It downplays exception handling in favour of explicit errors in return values. There is exactly one correct way to lay out Go code, enforced by the gofmt tool. And so on.

    Go is also a great language for writing concurrent programs: programs with many independently running parts. An obvious example is a webserver: Every request runs separately, but requests often need to share resources such as sessions, caches, or notification queues. This means skilled Go programmers need to deal with concurrent access to those resources.

    While the Go language has an excellent set of low-level features for handling concurrency, using them directly can become complicated. In many cases, a handful of reusable abstractions over those low-level mechanisms makes life much easier.

    In today’s Go programming tutorial, we’re going to look at one such abstraction: A wrapper which can turn any data structure into a transactional service. We’ll use a Fund type as an example – a simple store for our startup’s remaining funding, where we can check the balance and make withdrawals.

    In this introduction to programming in Go, we’ll build the service in small steps, making a mess along the way and then cleaning it up again. Along the way, we’ll encounter lots of cool Go features, including:

    • Struct types and methods
    • Unit tests and benchmarks
    • Goroutines and channels
    • Interfaces and dynamic typing

    A Simple Fund

    Let’s write some code to track our startup’s funding. The fund starts with a given balance, and money can only be withdrawn (we’ll figure out revenue later).

    This graphic depicts a simple goroutine example using the Go programming language.

    Go is deliberately not an object-oriented language: There are no classes, objects, or inheritance. Instead, we’ll declare a struct type called Fund, with a simple function to create new fund structs, and two public methods.

    fund.go

    package funding
    
    type Fund struct {
        // balance is unexported (private), because it's lowercase
        balance int
    }
    
    // A regular function returning a pointer to a fund
    func NewFund(initialBalance int) *Fund {
        // We can return a pointer to a new struct without worrying about
        // whether it's on the stack or heap: Go figures that out for us.
        return &Fund{
            balance: initialBalance,
        }
    }
    
    // Methods start with a *receiver*, in this case a Fund pointer
    func (f *Fund) Balance() int {
        return f.balance
    }
    
    func (f *Fund) Withdraw(amount int) {
        f.balance -= amount
    }
    

    Testing with benchmarks

    Next we need a way to test Fund. Rather than writing a separate program, we’ll use Go’s testing package, which provides a framework for both unit tests and benchmarks. The simple logic in our Fund isn’t really worth writing unit tests for, but since we’ll be talking a lot about concurrent access to the fund later on, writing a benchmark makes sense.

    Benchmarks are like unit tests, but include a loop which runs the same code many times (in our case, fund.Withdraw(1)). This allows the framework to time how long each iteration takes, averaging out transient differences from disk seeks, cache misses, process scheduling, and other unpredictable factors.

    The testing framework wants each benchmark to run for at least 1 second (by default). To ensure this, it will call the benchmark multiple times, passing in an increasing “number of iterations” value each time (the b.N field), until the run takes at least a second.

    For now, our benchmark will just deposit some money and then withdraw it one dollar at a time.

    fund_test.go

    package funding
    
    import "testing"
    
    func BenchmarkFund(b *testing.B) {
        // Add as many dollars as we have iterations this run
        fund := NewFund(b.N)
    
        // Burn through them one at a time until they are all gone
        for i := 0; i < b.N; i++ {
            fund.Withdraw(1)
        }
    
        if fund.Balance() != 0 {
            b.Error("Balance wasn't zero:", fund.Balance())
        }
    }
    

    Now let’s run it:

    $ go test -bench . funding
    testing: warning: no tests to run
    PASS
    BenchmarkWithdrawals    2000000000             1.69 ns/op
    ok      funding    3.576s
    

    That went well. We ran two billion (!) iterations, and the final check on the balance was correct. We can ignore the “no tests to run” warning, which refers to the unit tests we didn’t write (in later Go programming examples in this tutorial, the warning is snipped out).

    Concurrent Access

    Now let’s make the benchmark concurrent, to model different users making withdrawals at the same time. To do that, we’ll spawn ten goroutines and have each of them withdraw one tenth of the money.

    How would we structure muiltiple concurrent goroutines in the Go language?

    Goroutines are the basic building block for concurrency in the Go language. They are green threads – lightweight threads managed by the Go runtime, not by the operating system. This means you can run thousands (or millions) of them without any significant overhead. Goroutines are spawned with the go keyword, and always start with a function (or method call):

    // Returns immediately, without waiting for `DoSomething()` to complete
    go DoSomething()
    

    Often, we want to spawn off a short one-time function with just a few lines of code. In this case we can use a closure instead of a function name:

    go func() {
        // ... do stuff ...
    }() // Must be a function *call*, so remember the ()
    

    Once all our goroutines are spawned, we need a way to wait for them to finish. We could build one ourselves using channels, but we haven’t encountered those yet, so that would be skipping ahead.

    For now, we can just use the WaitGroup type in Go’s standard library, which exists for this very purpose. We’ll create one (called “wg”) and call wg.Add(1) before spawning each worker, to keep track of how many there are. Then the workers will report back using wg.Done(). Meanwhile in the main goroutine, we can just say wg.Wait() to block until every worker has finished.

    Inside the worker goroutines in our next example, we’ll use defer to call wg.Done().

    defer takes a function (or method) call and runs it immediately before the current function returns, after everything else is done. This is handy for cleanup:

    func() {
        resource.Lock()
        defer resource.Unlock()
    
        // Do stuff with resource
    }()
    

    This way we can easily match the Unlock with its Lock, for readability. More importantly, a deferred function will run even if there is a panic in the main function (something that we might handle via try-finally in other languages).

    Lastly, deferred functions will execute in the reverse order to which they were called, meaning we can do nested cleanup nicely (similar to the C idiom of nested gotos and labels, but much neater):

    func() {
        db.Connect()
        defer db.Disconnect()
    
        // If Begin panics, only db.Disconnect() will execute
        transaction.Begin()
        defer transaction.Close()
    
        // From here on, transaction.Close() will run first,
        // and then db.Disconnect()
    
        // ...
    }()
    

    OK, so with all that said, here’s the new version:

    fund_test.go

    package funding
    
    import (
        "sync"
        "testing"
    )
    
    const WORKERS = 10
    
    func BenchmarkWithdrawals(b *testing.B) {
        // Skip N = 1
        if b.N < WORKERS {
            return
        }
    
        // Add as many dollars as we have iterations this run
        fund := NewFund(b.N)
    
        // Casually assume b.N divides cleanly
        dollarsPerFounder := b.N / WORKERS
    
        // WaitGroup structs don't need to be initialized
        // (their "zero value" is ready to use).
        // So, we just declare one and then use it.
        var wg sync.WaitGroup
    
        for i := 0; i < WORKERS; i++ {
            // Let the waitgroup know we're adding a goroutine
            wg.Add(1)
            
            // Spawn off a founder worker, as a closure
            go func() {
                // Mark this worker done when the function finishes
                defer wg.Done()
    
                for i := 0; i < dollarsPerFounder; i++ {
                    fund.Withdraw(1)
                }
                
            }() // Remember to call the closure!
        }
    
        // Wait for all the workers to finish
        wg.Wait()
    
        if fund.Balance() != 0 {
            b.Error("Balance wasn't zero:", fund.Balance())
        }
    }
    

    We can predict what will happen here. The workers will all execute Withdraw on top of each other. Inside it, f.balance -= amount will read the balance, subtract one, and then write it back. But sometimes two or more workers will both read the same balance, and do the same subtraction, and we’ll end up with the wrong total. Right?

    $ go test -bench . funding
    BenchmarkWithdrawals    2000000000             2.01 ns/op
    ok      funding    4.220s
    

    No, it still passes. What happened here?

    Remember that goroutines are green threads – they’re managed by the Go runtime, not by the OS. The runtime schedules goroutines across however many OS threads it has available. At the time of writing this Go language tutorial, Go doesn’t try to guess how many OS threads it should use, and if we want more than one, we have to say so. Finally, the current runtime does not preempt goroutines – a goroutine will continue to run until it does something that suggests it’s ready for a break (like interacting with a channel).

    All of this means that although our benchmark is now concurrent, it isn’t parallel. Only one of our workers will run at a time, and it will run until it’s done. We can change this by telling Go to use more threads, via the GOMAXPROCS environment variable.

    $ GOMAXPROCS=4 go test -bench . funding
    BenchmarkWithdrawals-4    --- FAIL: BenchmarkWithdrawals-4
        account_test.go:39: Balance wasn't zero: 4238
    ok      funding    0.007s
    

    That’s better. Now we’re obviously losing some of our withdrawals, as we expected.

    In this Go programming example, the outcome of multiple parallel goroutines is not favorable.

    Make it a server

    At this point we have various options. We could add an explicit mutex or read-write lock around the fund. We could use a compare-and-swap with a version number. We could go all out and use a CRDT scheme (perhaps replacing the balance field with lists of transactions for each client, and calculating the balance from those).

    But we won’t do any of those things now, because they’re messy or scary or both. Instead, we’ll decide that a fund should be a server. What’s a server? It’s something you talk to. In Go, things talk via channels.

    Channels are the basic communication mechanism between goroutines. Values are sent to the channel (with channel <- value), and can be received on the other side (with value = <- channel). Channels are “goroutine safe”, meaning that any number of goroutines can send to and receive from them at the same time.

    By default, Go channels are unbuffered. This means that sending a value to a channel will block until another goroutine is ready to receive it immediately. Go also supports fixed buffer sizes for channels (using make(chan someType, bufferSize)). However, for normal use, this is usually a bad idea.

    Imagine a webserver for our fund, where each request makes a withdrawal. When things are very busy, the FundServer won’t be able to keep up, and requests trying to send to its command channel will start to block and wait. At that point we can enforce a maximum request count in the server, and return a sensible error code (like a 503 Service Unavailable) to clients over that limit. This is the best behavior possible when the server is overloaded.

    Adding buffering to our channels would make this behavior less deterministic. We could easily end up with long queues of unprocessed commands based on information the client saw much earlier (and perhaps for requests which had since timed out upstream). The same applies in many other situations, like applying backpressure over TCP when the receiver can’t keep up with the sender.

    In any case, for our Go example, we’ll stick with the default unbuffered behavior.

    We’ll use a channel to send commands to our FundServer. Every benchmark worker will send commands to the channel, but only the server will receive them.

    We could turn our Fund type into a server implementation directly, but that would be messy – we’d be mixing concurrency handling and business logic. Instead, we’ll leave the Fund type exactly as it is, and make FundServer a separate wrapper around it.

    Like any server, the wrapper will have a main loop in which it waits for commands, and responds to each in turn. There’s one more detail we need to address here: The type of the commands.

    A diagram of the fund being used as the server in this Go programming tutorial.

    In the next section below, we’ll be sending several different commands, each with its own struct type. We want the server’s Commands channel to accept any of them. In an OOP language we might do this via polymorphism: Have the channel take a superclass, of which the individual command types were subclasses. In Go, we use interfaces instead.

    An interface is a set of method signatures. Any type that implements all of those methods can be treated as that interface (without being declared to do so). For our first run, our command structs won’t actually expose any methods, so we’re going to use the empty interface, interface{}. Since it has no requirements, any value (including primitive values like integers) satisfies the empty interface. This isn’t ideal – we only want to accept command structs – but we’ll come back to it later.

    For now, let’s get started with the scaffolding for our server:

    server.go

    package funding
    
    type FundServer struct {
        Commands chan interface{}
        fund Fund
    }
    
    func NewFundServer(initialBalance int) *FundServer {
        server := &FundServer{
            // make() creates builtins like channels, maps, and slices
            Commands: make(chan interface{}),
            fund: NewFund(initialBalance),
        }
    
        // Spawn off the server's main loop immediately
        go server.loop()
        return server
    }
    
    func (s *FundServer) loop() {
        // The built-in "range" clause can iterate over channels,
        // amongst other things
        for command := range s.Commands {
        
            // Handle the command
            
        }
    }
    

    Now let’s add a couple of struct types for the commands:

    type WithdrawCommand struct {
        Amount int
    }
    
    type BalanceCommand struct {
        Response chan int
    }
    

    The WithdrawCommand just contains the amount to withdraw. There’s no response. The BalanceCommand does have a response, so it includes a channel to send it on. This ensures that responses will always go to the right place, even if our fund later decides to respond out-of-order.

    Now we can write the server’s main loop:

    func (s *FundServer) loop() {
        for command := range s.Commands {
    
            // command is just an interface{}, but we can check its real type
            switch command.(type) {
    
            case WithdrawCommand:
                // And then use a "type assertion" to convert it
                withdrawal := command.(WithdrawCommand)
                s.fund.Withdraw(withdrawal.Amount)
    
            case BalanceCommand:
                getBalance := command.(BalanceCommand)
                balance := s.fund.Balance()
                getBalance.Response <- balance
    
            default:
                panic(fmt.Sprintf("Unrecognized command: %v", command))
            }
        }
    }
    

    Hmm. That’s sort of ugly. We’re switching on the command type, using type assertions, and possibly crashing. Let’s forge ahead anyway and update the benchmark to use the server.

    func BenchmarkWithdrawals(b *testing.B) {
        // ...
    
        server := NewFundServer(b.N)
    
        // ...
    
        // Spawn off the workers
        for i := 0; i < WORKERS; i++ {
            wg.Add(1)
            go func() {
                defer wg.Done()
                for i := 0; i < dollarsPerFounder; i++ {
                    server.Commands <- WithdrawCommand{ Amount: 1 }
                }
            }()
        }
    
        // ...
    
        balanceResponseChan := make(chan int)
        server.Commands <- BalanceCommand{ Response: balanceResponseChan }
        balance := <- balanceResponseChan
    
        if balance != 0 {
            b.Error("Balance wasn't zero:", balance)
        }
    }
    

    That was sort of ugly too, especially when we checked the balance. Never mind. Let’s try it:

    $ GOMAXPROCS=4 go test -bench . funding
    BenchmarkWithdrawals-4     5000000           465 ns/op
    ok      funding    2.822s
    

    Much better, we’re no longer losing withdrawals. But the code is getting hard to read, and there are more serious problems. If we ever issue a BalanceCommand and then forget to read the response, our fund server will block forever trying to send it. Let’s clean things up a bit.

    Make it a service

    A server is something you talk to. What’s a service? A service is something you talk to with an API. Instead of having client code work with the command channel directly, we’ll make the channel unexported (private) and wrap the available commands up in functions.

    type FundServer struct {
        commands chan interface{} // Lowercase name, unexported
        // ...
    }
    
    func (s *FundServer) Balance() int {
        responseChan := make(chan int)
        s.commands <- BalanceCommand{ Response: responseChan }
        return <- responseChan
    }
    
    func (s *FundServer) Withdraw(amount int) {
        s.commands <- WithdrawCommand{ Amount: amount }
    }
    

    Now our benchmark can just say server.Withdraw(1) and balance := server.Balance(), and there’s less chance of accidentally sending it invalid commands or forgetting to read responses.

    Here is what using the fund as a service might look like in this sample Go language program.

    There’s still a lot of extra boilerplate for the commands, but we’ll come back to that later.

    Transactions

    Eventually, the money always runs out. Let’s agree that we’ll stop withdrawing when our fund is down to its last ten dollars, and spend that money on a communal pizza to celebrate or commiserate around. Our benchmark will reflect this:

    // Spawn off the workers
    for i := 0; i < WORKERS; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for i := 0; i < dollarsPerFounder; i++ {
    
                // Stop when we're down to pizza money
                if server.Balance() <= 10 {
                    break
                }
                server.Withdraw(1)
            }
        }()
    }
    
    // ...
    
    balance := server.Balance()
    if balance != 10 {
        b.Error("Balance wasn't ten dollars:", balance)
    }
    

    This time we really can predict the result.

    $ GOMAXPROCS=4 go test -bench . funding
    BenchmarkWithdrawals-4    --- FAIL: BenchmarkWithdrawals-4
        fund_test.go:43: Balance wasn't ten dollars: 6
    ok      funding    0.009s
    

    We’re back where we started – several workers can read the balance at once, and then all update it. To deal with this we could add some logic in the fund itself, like a minimumBalance property, or add another command called WithdrawIfOverXDollars. These are both terrible ideas. Our agreement is amongst ourselves, not a property of the fund. We should keep it in application logic.

    What we really need is transactions, in the same sense as database transactions. Since our service executes only one command at a time, this is super easy. We’ll add a Transact command which contains a callback (a closure). The server will execute that callback inside its own goroutine, passing in the raw Fund. The callback can then safely do whatever it likes with the Fund.

    // Typedef the callback for readability
    type Transactor func(fund *Fund)
    
    // Add a new command type with a callback and a semaphore channel
    type TransactionCommand struct {
        Transactor Transactor
        Done chan bool
    }
    
    // ...
    
    // Wrap it up neatly in an API method, like the other commands
    func (s *FundServer) Transact(transactor Transactor) {
        command := TransactionCommand{
            Transactor: transactor,
            Done: make(chan bool),
        }
        s.commands <- command
        <- command.Done
    }
    
    // ...
    
    func (s *FundServer) loop() {
        for command := range s.commands {
            switch command.(type) {
            // ...
    
            case TransactionCommand:
                transaction := command.(TransactionCommand)
                transaction.Transactor(s.fund)
                transaction.Done <- true
    
            // ...
            }
        }
    }
    

    Our transaction callbacks don’t directly return anything, but the Go language makes it easy to get values out of a closure directly, so we’ll do that in the benchmark to set the pizzaTime flag when money runs low:

    pizzaTime := false
    for i := 0; i < dollarsPerFounder; i++ {
    
        server.Transact(func(fund *Fund) {
            if fund.Balance() <= 10 {
                // Set it in the outside scope
                pizzaTime = true
                return
            }
            fund.Withdraw(1)
        })
    
        if pizzaTime {
            break
        }
    }
    

    And check that it works:

    $ GOMAXPROCS=4 go test -bench . funding
    BenchmarkWithdrawals-4     5000000           775 ns/op
    ok      funding    4.637s
    

    Nothing But transactions

    You may have spotted an opportunity to clean things up some more now. Since we have a generic Transact command, we don’t need WithdrawCommand or BalanceCommand anymore. We’ll rewrite them in terms of transactions:

    func (s *FundServer) Balance() int {
        var balance int
        s.Transact(func(f *Fund) {
            balance = f.Balance()
        })
        return balance
    }
    
    func (s *FundServer) Withdraw(amount int) {
        s.Transact(func (f *Fund) {
            f.Withdraw(amount)
        })
    }
    

    Now the only command the server takes is TransactionCommand, so we can remove the whole interface{} mess in its implementation, and have it accept only transaction commands:

    type FundServer struct {
        commands chan TransactionCommand
        fund *Fund
    }
    
    func (s *FundServer) loop() {
        for transaction := range s.commands {
            // Now we don't need any type-switch mess
            transaction.Transactor(s.fund)
            transaction.Done <- true
        }
    }
    

    Much better.

    There’s a final step we could take here. Apart from its convenience functions for Balance and Withdraw, the service implementation is no longer tied to Fund. Instead of managing a Fund, it could manage an interface{} and be used to wrap anything. However, each transaction callback would then have to convert the interface{} back to a real value:

    type Transactor func(interface{})
    
    server.Transact(func(managedValue interface{}) {
        fund := managedValue.(*Fund)
        // Do stuff with fund ...
    })
    

    This is ugly and error-prone. What we really want is compile-time generics, so we can “template” out a server for a particular type (like *Fund).

    Unfortunately, Go doesn’t support generics – yet. It’s expected to arrive eventually, once someone figures out some sensible syntax and semantics for it. In the meantime, careful interface design often removes the need for generics, and when they don’t we can get by with type assertions (which are checked at runtime).

  • GO PROGRAMMING LAUNGAGE SETUP ENVIROMENT ↓

    Text Editor

    This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.

    Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX.

    The files you create with your editor are called source files and contain program source code. The source files for Go programs are typically named with the extension ".go".

    Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, compile it and finally execute it.

    The Go Compiler

    The source code written in source file is the human readable source for your program. It needs to be "compiled", to turn into machine language so that your CPU can actually execute the program as per instructions given.

    This Go programming language compiler will be used to compile your source code into final executable program. I assume you have basic knowledge about a programming language compiler.

    Go distribution comes as a binary installable for FreeBSD (release 8 and above), Linux, Mac OS X (Snow Leopard and above), and Windows operating systems with the 32-bit (386) and 64-bit (amd64) x86 processor architectures.

    Following section guides you on how to install Go binary distribution on various OS.

    Download Go archive

    Download latest version of Go installable archive file from Go Downloads. At the time of writing this tutorial, I downloaded go1.4.windows-amd64.msi and copied it into C:\>go folder.

    OSArchive name
    Windowsgo1.4.windows-amd64.msi
    Linuxgo1.4.linux-amd64.tar.gz
    Macgo1.4.darwin-amd64-osx10.8.pkg
    FreeBSDgo1.4.freebsd-amd64.tar.gz

    Installation on UNIX/Linux/Mac OS X, and FreeBSD

    Extract the download archive into /usr/local, creating a Go tree in /usr/local/go. For example:

    tar -C /usr/local -xzf go1.4.linux-amd64.tar.gz

    Add /usr/local/go/bin to the PATH environment variable.

    OSOutput
    Linuxexport PATH=$PATH:/usr/local/go/bin
    Macexport PATH=$PATH:/usr/local/go/bin
    FreeBSDexport PATH=$PATH:/usr/local/go/bin

    Installation on Windows

    Use the MSI file and follow the prompts to install the Go tools. By default, the installer uses the Go distribution in c:\Go. The installer should set the c:\Go\bin directory in window's PATH environment variable. Restart any open command prompts for the change to take effect.

    Verify installation

    Create a go file named test.go in C:\>Go_WorkSpace.

    File: test.go

    package main
    
    import "fmt"
    
    func main() {
       fmt.Println("Hello, World!")
    }
    

    Now run the test.go to see the result:

    C:\Go_WorkSpace>go run test.go
    

    Verify the Output

    Hello, World!
    

  • GO PACKAGES ↓

    Packages

    Every Go program is made up of packages.

    Programs start running in package main.

    This program is using the packages with import paths "fmt" and "math/rand".

    By convention, the package name is the same as the last element of the import path. For instance, the "math/rand" package comprises files that begin with the statement package rand.

    Note: the environment in which these programs are executed is deterministic, so each time you run the example program rand.Intn will return the same number. (To see a different number, seed the number generator; see rand.Seed.)

      package main
    
    import (
    	"fmt"
    	"math/rand"
    )
    
    func main() {
    	fmt.Println("My favorite number is", rand.Intn(10))
    }
    
      

    --Output is

      My favorite number is 1
      
  • GO IMPORTS ↓

    This code groups the imports into a parenthesized, "factored" import statement.

    You can also write multiple import statements, like:

    import "fmt"
    import "math"

    But it is good style to use the factored import statement.

      package main
    
    import (
    	"fmt"
    	"math"
    )
    
    func main() {
    	fmt.Printf("Now you have %g problems.", math.Nextafter(2, 3))
    }
      

    --Output is

      Now you have 2.0000000000000004 problems.
      
  • GO BASIC SYNTAX ↓

    You have seen a basic structure of Go program, so it will be easy to understand other basic building blocks of the Go programming language.

    Tokens in Go

    A Go program consists of various tokens and 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!")
    

    The individual tokens are:

    fmt
    .
    Println
    (
    "Hello, World!"
    )
    

    Line Seperator

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

    For example, following are two different statements:

    fmt.Println("Hello, World!")
    fmt.Println("I am in Go Programming World!")
    

    Comments

    Comments are like helping text in your Go program and they are ignored by the compiler. They start with /* and terminates with the characters */ as shown below:

    /* my first program in Go */
    

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

    Identifiers

    A Go identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or more letters, underscores, and digits (0 to 9).

    identifier = letter { letter | unicode_digit } .

    Go does not allow punctuation characters such as @, $, and % within identifiers. Go is a case sensitive programming language. Thus, Manpower and manpower are two different identifiers in Go. Here are some examples of acceptable identifiers:

    mahesh   kumar   abc   move_name   a_123
    myname50   _temp   j   a23b9   retVal
    

    Keywords

    The following list shows the reserved words in Go. These reserved words may not be used as constant or variable or any other identifier names.

    breakdefaultfuncinterfaceselect
    casedefergomapstruct
    chanelsegotopackageswitch
    constfallthroughifrangetype
    continueforimportreturnvar

    Whitespace in Go

    A line containing only whitespace, possibly with a comment, is known as a blank line, and a Go compiler totally ignores it.

    Whitespace is the term used in Go to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement:

    var age int;
    

    There must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them. On the other hand, in the following statement:

    fruit = apples + oranges;   // get the total fruit
    

    No whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish for readability purpose.


  • GO DATA TYPES ↓

    In the Go programming language, data types refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted.

    The types in Go can be classified as follows:

    S.N.Types and Description
    1Boolean Types
    They are boolean types and consists of the two predefined constants: (a) true (b) false
    2Numeric Types
    They are again arithmetic types and they represents a) integer types or b) floating point values throughout the program.
    3string types:
    A string type represents the set of string values. Its value is a sequence of bytes. Strings are immutable types that is once created, it is not possible to change the contents of a string. The predeclared string type is string.
    4Derived types:
    They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function types f) Slice types g) Function types h) Interface types i) Map types j) Channel Types

    The array types and structure types are referred to collectively as the aggregate types. The type of a function specifies the set of all functions with the same parameter and result types. We will see basic types in the following section, whereas, other types will be covered in the upcoming chapters.

    Integer Types

    The predefine architecture-independent integer types are:

    S.N.Types and Description
    1uint8
    Unsigned 8-bit integers (0 to 255)
    2uint16
    Unsigned 16-bit integers (0 to 65535)
    3uint32
    Unsigned 32-bit integers (0 to 4294967295)
    4uint64
    Unsigned 64-bit integers (0 to 18446744073709551615)
    5int8
    Signed 8-bit integers (-128 to 127)
    6int16
    Signed 16-bit integers (-32768 to 32767)
    7int32
    Signed 32-bit integers (-2147483648 to 2147483647)
    8int64
    Signed 64-bit integers (-9223372036854775808 to 9223372036854775807)

    Floating Types

    The predefine architecture-independent float types are:

    S.N.Types and Description
    1float32
    IEEE-754 32-bit floating-point numbers
    2float64
    IEEE-754 64-bit floating-point numbers
    3complex64
    Complex numbers with float32 real and imaginary parts
    4complex128
    Complex numbers with float64 real and imaginary parts

    The value of an n-bit integer is n bits and is represented using two's complement arithmetic operations.

    Other Numeric Types

    There is also a set of numeric types with implementation-specific sizes:

    S.N.Types and Description
    1byte
    same as uint8
    2rune
    same as int32
    3uint
    32 or 64 bits
    4int
    same size as uint
    5uintptr
    an unsigned integer to store the uninterpreted bits of a pointer value
  • GO VARIABLES ↓

    A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in Go has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

    The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Go is case-sensitive. Based on the basic types explained in previous chapter, there will be the following basic variable types:

    TypeDescription
    byteTypically a single octet(one byte). This is an byte type.
    intThe most natural size of integer for the machine.
    float32A single-precision floating point value.

    Go programming language also allows to define various other types of variables, which we will cover in subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc. For this chapter, let us study only basic variable types.

    Variable Definition in Go:

    A variable definition means to tell the compiler where and how much to create the storage for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows:

    var variable_list optional_data_type;
    

    Here, optional_data_type is a valid Go data type including byte, int, float32, complex64, boolean or any user-defined object, etc., and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here:

    var    i, j, k int;
    var   c, ch byte;
    var  f, salary float32;
    d = 42;
    

    The line var i, j, k; both declares and defines the variables i, j and k; which instructs the compiler to create variables named i, j and k of type int.

    Variables can be initialized (assigned an initial value) in their declaration. The type of variable is automatically judged by the compiler based on the value passed to it. The initializer consists of an equal sign followed by a constant expression as follows:

    variable_name = value;
    

    Some examples are:

    d = 3, f = 5;    // declaration of d and f. Here d and f are int 
    

    For definition without an initializer: variables with static storage duration are implicitly initialized with nil (all bytes have the value 0); the initial value of all other variables is zero value of their data type.

    Static type declaration

    A static type variable declaration provides assurance to the compiler that there is one variable existing with the given type and name so that compiler proceed for further compilation without needing complete detail about the variable. A variable declaration has its meaning at the time of compilation only, compiler needs actual variable declaration at the time of linking of the program.

    Example

    Try following example, where variable has been declared with a type, and have been defined and initialized inside the main function:

    package main
    
    import "fmt"
    
    func main() {
       var x float64
       x = 20.0
       fmt.Println(x)
       fmt.Printf("x is of type %T\n", x)
    }
    

    When the above code is compiled and executed, it produces the following result:

    20 x is of type float64

    Dynamic type declaration / Type Inference

    A dynamic type variable declaration requires compiler to interpret the type of variable based on value passed to it. Compiler don't need a variable to have type statically as a necessary requirement.

    Example

    Try following example, where variables have been declared without any type, and have been defined and initialized inside the main function. Notice, in case of type inference, we've initialized the variable y with := operator wheree as x is initilized using = operator.

    package main
    
    import "fmt"
    
    func main() {
       var x float64 = 20.0
    
       y := 42 
       fmt.Println(x)
       fmt.Println(y)
       fmt.Printf("x is of type %T\n", x)
       fmt.Printf("y is of type %T\n", y)	
    }
    

    When the above code is compiled and executed, it produces the following result:

    20 42 x is of type float64 y is of type int

    Mixed variable declaration

    Variables of different types can be declared in one go using type inference.

    Example

    package main
    
    import "fmt"
    
    func main() {
       var a, b, c = 3, 4, "foo"  
    	
       fmt.Println(a)
       fmt.Println(b)
       fmt.Println(c)
       fmt.Printf("a is of type %T\n", a)
       fmt.Printf("b is of type %T\n", b)
       fmt.Printf("c is of type %T\n", c)
    }
    

    When the above code is compiled and executed, it produces the following result:

    3 4 foo a is of type int b is of type int c is of type string

    Lvalues and Rvalues in Go:

    There are two kinds of expressions in Go:

    1. lvalue : Expressions that refer to a memory location is called "lvalue" expression. An lvalue may appear as either the left-hand or right-hand side of an assignment.

    2. rvalue : The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment.

    Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a valid statement:

    x = 20.0
    

    But following is not a valid statement and would generate compile-time error:

    10 = 20
    
  • GO OPERATORS ↓

    An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Go language is rich in built-in operators and provides the following types of operators:

    • Arithmetic Operators

    • Relational Operators

    • Logical Operators

    • Bitwise Operators

    • Assignment Operators

    • Misc Operators

    This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

    Arithmetic Operators

    Following table shows all the arithmetic operators supported by Go language. Assume variable A holds 10 and variable B holds 20 then:

    OperatorDescriptionExample
    +Adds two operands A + B will give 30
    -Subtracts second operand from the first A - B will give -10
    *Multiplies both operands A * B will give 200
    /Divides numerator by de-numerator B / A will give 2
    %Modulus Operator and remainder of after an integer division B % A will give 0
    ++Increments operator increases integer value by one A++ will give 11
    --Decrements operator decreases integer value by one A-- will give 9

    Relational Operators

    Following table shows all the relational operators supported by Go language. Assume variable A holds 10 and variable B holds 20, then:

    OperatorDescriptionExample
    == Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true.
    != Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true.
    > Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true.
    < Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true.
    >= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true.
    <= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true.

    Logical Operators

    Following table shows all the logical operators supported by Go language. Assume variable A holds 1 and variable B holds 0, then:

    OperatorDescriptionExample
    && Called Logical AND operator. If both the operands are non-zero, then condition becomes true. (A && B) is false.
    ||Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true. (A || B) is true.
    !Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is true.

    Bitwise Operators

    Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows:

    pqp & qp | qp ^ q
    00000
    01011
    11110
    10011

    Assume if A = 60; and B = 13; now in binary format they will be as follows:

    A = 0011 1100

    B = 0000 1101

    -----------------

    A&B = 0000 1100

    A|B = 0011 1101

    A^B = 0011 0001

    ~A  = 1100 0011

    The Bitwise operators supported by C language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then:

    OperatorDescriptionExample
    & Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12, which is 0000 1100
    | Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61, which is 0011 1101
    ^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) will give 49, which is 0011 0001
    << Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 will give 240 which is 1111 0000
    >> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 will give 15 which is 0000 1111

    Assignment Operators

    There are following assignment operators supported by Go language:

    OperatorDescriptionExample
    =Simple assignment operator, Assigns values from right side operands to left side operand C = A + B will assign value of A + B into C
    +=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand C += A is equivalent to C = C + A
    -=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand C -= A is equivalent to C = C - A
    *=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand C *= A is equivalent to C = C * A
    /=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand C /= A is equivalent to C = C / A
    %=Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand C %= A is equivalent to C = C % A
    <<=Left shift AND assignment operator C <<= 2 is same as C = C << 2
    >>=Right shift AND assignment operator C >>= 2 is same as C = C >> 2
    &=Bitwise AND assignment operator C &= 2 is same as C = C & 2
    ^=bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
    |=bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2

    Misc Operators

    There are few other important operators including sizeof and ? : supported by Go Language.

    OperatorDescriptionExample
    &Returns the address of an variable.&a; will give actual address of the variable.
    *Pointer to a variable.*a; will pointer to a variable.

    Operators Precedence in Go

    Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator.

    For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

    Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

    Category  Operator Associativity 
    Postfix () [] -> . ++ - -   Left to right 
    Unary  + - ! ~ ++ - - (type)* & sizeof  Right to left 
    Multiplicative   * / % Left to right 
    Additive  + -  Left to right 
    Shift   << >>  Left to right 
    Relational  < <= > >=  Left to right 
    Equality   == !=  Left to right 
    Bitwise AND  Left to right 
    Bitwise XOR  Left to right 
    Bitwise OR  Left to right 
    Logical AND &&  Left to right 
    Logical OR  ||  Left to right 
    Conditional ?:  Right to left 
    Assignment  = += -= *= /= %=>>= <<= &= ^= |= Right to left 
    Comma  Left to right 
  • GO DECISION MAKING (IF, ELSE IF, NESTED IF, SWITCH & SELECT STATEMENT ↓

    Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

    Following is the general form of a typical decision making structure found in most of the programming languages:

    Decision making statements in Go

    Go programming language provides following types of decision making statements. Click the following links to check their detail.

    StatementDescription
    if statementAn if statement consists of a boolean expression followed by one or more statements.
    if...else statementAn if statement can be followed by an optional else statement, which executes when the boolean expression is false.
    nested if statementsYou can use one if or else if statement inside another if or else if statement(s).
    switch statementA switch statement allows a variable to be tested for equality against a list of values.
    select statementA select statement is similar to switch statement with difference as case statements refers to channel communications.

    IF STATEMENT

    If the boolean expression evaluates to true, then the block of code inside the if statement will be executed. If boolean expression evaluates to false, then the first set of code after the end of the if statement(after the closing curly brace) will be executed.

    Flow Diagram:

    Go if statement

    Example:

    package main
    
    import "fmt"
    
    func main() {
       /* local variable definition */
       var a int = 10
     
       /* check the boolean condition using if statement */
       if( a < 20 ) {
           /* if condition is true then print the following */
           fmt.Printf("a is less than 20\n" )
       }
       fmt.Printf("value of a is : %d\n", a)
    }
    

    When the above code is compiled and executed, it produces the following result:

    a is less than 20;
    value of a is : 10
    

    Else if Statement

    An if statement can be followed by an optional else statement, which executes when the boolean expression is false.

    Syntax:

    The syntax of an if...else statement in Go programming language is:

    if(boolean_expression)
    {
       /* statement(s) will execute if the boolean expression is true */
    }
    else
    {
      /* statement(s) will execute if the boolean expression is false */
    }
    

    If the boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code will be executed.

    Flow Diagram:

    Go if...else statement

    Example:

    package main
    
    import "fmt"
    
    func main() {
       /* local variable definition */
       var a int = 100;
     
       /* check the boolean condition */
       if( a < 20 ) {
           /* if condition is true then print the following */
           fmt.Printf("a is less than 20\n" );
       } else {
           /* if condition is false then print the following */
           fmt.Printf("a is not less than 20\n" );
       }
       fmt.Printf("value of a is : %d\n", a);
    
    }
    

    When the above code is compiled and executed, it produces the following result:

    a is not less than 20;
    value of a is : 100
    

    The if...else if...else Statement

    An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement.

    When using if , else if , else statements there are few points to keep in mind:

    • An if can have zero or one else's and it must come after any else if's.

    • An if can have zero to many else if's and they must come before the else.

    • Once an else if succeeds, none of the remaining else if's or else's will be tested.

    Syntax:

    The syntax of an if...else if...else statement in Go programming language is:

    if(boolean_expression 1)
    {
       /* Executes when the boolean expression 1 is true */
    }
    else if( boolean_expression 2)
    {
       /* Executes when the boolean expression 2 is true */
    }
    else if( boolean_expression 3)
    {
       /* Executes when the boolean expression 3 is true */
    }
    else 
    {
       /* executes when the none of the above condition is true */
    }
    

    Example:

    package main
    
    import "fmt"
    
    func main() {
       /* local variable definition */
       var a int = 100
     
       /* check the boolean condition */
       if( a == 10 ) {
           /* if condition is true then print the following */
           fmt.Printf("Value of a is 10\n" )
       } else if( a == 20 ) {
           /* if else if condition is true */
           fmt.Printf("Value of a is 20\n" )
       } else if( a == 30 ) {
           /* if else if condition is true  */
           fmt.Printf("Value of a is 30\n" )
       } else {
           /* if none of the conditions is true */
           fmt.Printf("None of the values is matching\n" )
       }
       fmt.Printf("Exact value of a is: %d\n", a )
    }
    

    When the above code is compiled and executed, it produces the following result:

    None of the values is matching
    Exact value of a is: 100
    

    Nasted if Statement

    It is always legal in Go programming to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement(s).

    Syntax:

    The syntax for a nested if statement is as follows:

    if( boolean_expression 1)
    {
       /* Executes when the boolean expression 1 is true */
       if(boolean_expression 2)
       {
          /* Executes when the boolean expression 2 is true */
       }
    }
    

    You can nest else if...else in the similar way as you have nested if statement.

    Example:

    package main
    
    import "fmt"
    
    func main() {
       /* local variable definition */
       var a int = 100
       var b int = 200
     
       /* check the boolean condition */
       if( a == 100 ) {
           /* if condition is true then check the following */
           if( b == 200 )  {
              /* if condition is true then print the following */
              fmt.Printf("Value of a is 100 and b is 200\n" );
           }
       }
       fmt.Printf("Exact value of a is : %d\n", a );
       fmt.Printf("Exact value of b is : %d\n", b );
    }
    

    When the above code is compiled and executed, it produces the following result:

    Value of a is 100 and b is 200
    Exact value of a is : 100
    Exact value of b is : 200
    

    Switch Statement

    A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.

    In Go programming, switch are of two types.

    • Expression Switch - In expression switch, a case contains expressions which is compared against the value of the switch expression.

    • Type Switch - In type switch, a case contain type which is compared against the type of a specially annotated switch expression.

    Expression Switch

    The syntax for a expression switch statement in Go programming language is as follows:

    switch(boolean-expression or integral type){
        case boolean-expression or integral type  :
           statement(s);      
        case boolean-expression or integral type  :
           statement(s); 
        /* you can have any number of case statements */
        default : /* Optional */
           statement(s);
    }
    

    The following rules apply to a switch statement:

    • The expression used in a switch statement must have an integral or boolean expression, or be of a class type in which the class has a single conversion function to an integral or boolean value. If expression is not passed than default value is true.

    • You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.

    • The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.

    • When the variable being switched on is equal to a case, the statements following that case will execute.No break is needed in the case statement.

    • A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

    Flow Diagram:

    switch statement in Go

    Example:

    package main
    
    import "fmt"
    
    func main() {
       /* local variable definition */
       var grade string = "B"
       var marks int = 90
    
       switch marks {
          case 90: grade = "A"
          case 80: grade = "B"
          case 50,60,70 : grade = "C"
          default: grade = "D"  
       }
    
       switch {
          case grade == "A" :
             fmt.Printf("Excellent!\n" )     
          case grade == "B", grade == "C" :
             fmt.Printf("Well done\n" )      
          case grade == "D" :
             fmt.Printf("You passed\n" )      
          case grade == "F":
             fmt.Printf("Better try again\n" )
          default:
             fmt.Printf("Invalid grade\n" );
       }
       fmt.Printf("Your grade is  %s\n", grade );      
    }
    

    When the above code is compiled and executed, it produces the following result:

    Well done
    Excellent!
    Your grade is  A
    

    Type Switch

    The syntax for a type switch statement in Go programming language is as follows:

    switch x.(type){
        case type:
           statement(s);      
        case type:
           statement(s); 
        /* you can have any number of case statements */
        default: /* Optional */
           statement(s);
    }
    

    The following rules apply to a switch statement:

    • The expression used in a switch statement must have an variable of interface{} type.

    • You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.

    • The type for a case must be the same data type as the variable in the switch, and it must be a valid data type.

    • When the variable being switched on is equal to a case, the statements following that case will execute.No break is needed in the case statement.

    • A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

    Example:

    package main
    
    import "fmt"
    
    func main() {
       var x interface{}
         
       switch i := x.(type) {
          case nil:	  
             fmt.Printf("type of x :%T",i)                
          case int:	  
             fmt.Printf("x is int")                       
          case float64:
             fmt.Printf("x is float64")           
          case func(int) float64:
             fmt.Printf("x is func(int)")                      
          case bool, string:
             fmt.Printf("x is bool or string")       
          default:
             fmt.Printf("don't know the type")     
       }   
    }
    

    When the above code is compiled and executed, it produces the following result:

    type of x :<nil>
    

    Select Statement

    The following rules apply to a select statement:

    • You can have any number of case statements within a select. Each case is followed by the value to be compared to and a colon.

    • The type for a case must be the a communication channel operation.

    • When the channel operation occured the statements following that case will execute.No break is needed in the case statement.

    • A select statement can have an optional default case, which must appear at the end of the select. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

    Example:

    package main
    
    import "fmt"
    
    func main() {
       var c1, c2, c3 chan int
       var i1, i2 int
       select {
          case i1 = <-c1:
             fmt.Printf("received ", i1, " from c1\n")
          case c2 <- i2:
             fmt.Printf("sent ", i2, " to c2\n")
          case i3, ok := (<-c3):  // same as: i3, ok := <-c3
             if ok {
                fmt.Printf("received ", i3, " from c3\n")
             } else {
                fmt.Printf("c3 is closed\n")
             }
          default:
             fmt.Printf("no communication\n")
       }    
    }   
    

    When the above code is compiled and executed, it produces the following result:

    no communication
    
  • GO LOOPS, FOR, NASTED FOR, CONTROL STATEMENT:BREAK, CONTINUE, GOTO ↓

    There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.

    Programming languages provide various control structures that allow for more complicated execution paths.

    A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages:

    Loop Architecture

    Go programming language provides the following types of loop to handle looping requirements. Click the following links to check their detail.

    Loop TypeDescription
    for loopExecute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
    nested loopsYou can use one or more for loop inside any for loop.

    Examples

    A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

    Syntax:

    The syntax of a for loop in Go programming language is:

    for [condition |  ( init; condition; increment ) | Range]
    {
       statement(s);
    }
    

    Here is the flow of control in a for loop:

    1. if condition is available, then for loop executes as long as condition is true.

    2. if for clause that is ( init; condition; increment ) is present then

      1. The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.

      2. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.

      3. After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.

      4. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates.

    3. if range is available, then for loop executes for each item in the range.

    Flow Diagram:

    for loop in Go

    Example:

    package main
    
    import "fmt"
    
    func main() {
       
       var b int = 15
       var a int
    
       numbers := [6]int{1, 2, 3, 5} 
    
       /* for loop execution */
       for a := 0; a < 10; a++ {
          fmt.Printf("value of a: %d\n", a)
       }
    
       for a < b {
          a++
          fmt.Printf("value of a: %d\n", a)
          }
    
       for i,x:= range numbers {
          fmt.Printf("value of x = %d at %d\n", x,i)
       }   
    }
    

    When the above code is compiled and executed, it produces the following result:

    value of a: 0
    value of a: 1
    value of a: 2
    value of a: 3
    value of a: 4
    value of a: 5
    value of a: 6
    value of a: 7
    value of a: 8
    value of a: 9
    value of a: 1
    value of a: 2
    value of a: 3
    value of a: 4
    value of a: 5
    value of a: 6
    value of a: 7
    value of a: 8
    value of a: 9
    value of a: 10
    value of a: 11
    value of a: 12
    value of a: 13
    value of a: 14
    value of a: 15
    value of x = 1 at 0
    value of x = 2 at 1
    value of x = 3 at 2
    value of x = 5 at 3
    value of x = 0 at 4
    value of x = 0 at 5
    

    Go Nasted For Loop

    Go programming language allows to use one loop inside another loop. Following section shows few examples to illustrate the concept.

    Syntax:

    The syntax for a nested for loop statement in Go is as follows:

    for [condition |  ( init; condition; increment ) | Range]
    {
       for [condition |  ( init; condition; increment ) | Range]
       {
          statement(s);
       }
       statement(s);
    }
    

    Example:

    The following program uses a nested for loop to find the prime numbers from 2 to 100:

    package main
    
    import "fmt"
    
    func main() {
       /* local variable definition */
       var i, j int
    
       for i=2; i < 100; i++ {
          for j=2; j <= (i/j); j++ {
             if(i%j==0) {
                break; // if factor found, not prime
             }
          }
          if(j > (i/j)) {
             fmt.Printf("%d is prime\n", i);
          }
       }  
    }
    

    When the above code is compiled and executed, it produces the following result:

    2 is prime
    3 is prime
    5 is prime
    7 is prime
    11 is prime
    13 is prime
    17 is prime
    19 is prime
    23 is prime
    29 is prime
    31 is prime
    37 is prime
    41 is prime
    43 is prime
    47 is prime
    53 is prime
    59 is prime
    61 is prime
    67 is prime
    71 is prime
    73 is prime
    79 is prime
    83 is prime
    89 is prime
    97 is prime
    

    Loop Control Statements:

    Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

    C supports the following control statements. Click the following links to check their detail.

    Control StatementDescription
    break statementTerminates the for loop or switch statement and transfers execution to the statement immediately following the for loop or switch.
    continue statementCauses the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
    goto statementTransfers control to the labeled statement.

    Break Statement

    The break statement in Go programming language has the following two usages:

    1. When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.

    2. It can be used to terminate a case in the switch statement.

    If you are using nested loops (i.e., one loop inside another loop), the break statement will stop the execution of the innermost loop and start executing the next line of code after the block.

    Syntax:

    The syntax for a break statement in Go is as follows:

    break;
    

    Flow Diagram:

    Go break statement

    Example:

    package main
    
    import "fmt"
    
    func main() {
       /* local variable definition */
       var a int = 10
    
       /* for loop execution */
       for a < 20 {
          fmt.Printf("value of a: %d\n", a);
          a++;
          if a > 15 {
             /* terminate the loop using break statement */
             break;
          }
       }
    }
    

    When the above code is compiled and executed, it produces the following result:

    value of a: 10
    value of a: 11
    value of a: 12
    value of a: 13
    value of a: 14
    value of a: 15
    

    Continue Statement

    The continue statement in Go programming language works somewhat like the break statement. Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any code in between.

    For the for loop, continue statement causes the conditional test and increment portions of the loop to execute.

    Syntax:

    The syntax for a continue statement in Go is as follows:

    continue;
    

    Flow Diagram:

    Go continue statement

    Example:

    package main
    
    import "fmt"
    
    func main() {
       /* local variable definition */
       var a int = 10
    
       /* do loop execution */
       for a < 20 {
          if a == 15 {
             /* skip the iteration */
             a = a + 1;
             continue;
          }
          fmt.Printf("value of a: %d\n", a);
          a++;     
       }  
    }
    

    When the above code is compiled and executed, it produces the following result:

    value of a: 10
    value of a: 11
    value of a: 12
    value of a: 13
    value of a: 14
    value of a: 16
    value of a: 17
    value of a: 18
    value of a: 19
    

    GoTo Statement

    A goto statement in Go programming language provides an unconditional jump from the goto to a labeled statement in the same function.

    NOTE: Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten so that it doesn't need the goto.

    Syntax:

    The syntax for a goto statement in Go is as follows:

    goto label;
    ..
    .
    label: statement;
    

    Here label can be any plain text except Go keyword and it can be set anywhere in the Go program above or below to goto statement.

    Flow Diagram:

    Go goto statement

    Example:

    package main
    
    import "fmt"
    
    func main() {
       /* local variable definition */
       var a int = 10
    
       /* do loop execution */
       LOOP: for a < 20 {
          if a == 15 {
             /* skip the iteration */
             a = a + 1
             goto LOOP
          }
          fmt.Printf("value of a: %d\n", a)
          a++     
       }  
    }
    

    When the above code is compiled and executed, it produces the following result:

    value of a: 10
    value of a: 11
    value of a: 12
    value of a: 13
    value of a: 14
    value of a: 16
    value of a: 17
    value of a: 18
    value of a: 19
    

    The Infinite Loop:

    A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty or pass true to it.

    package main
    
    import "fmt"
    
    func main() {
       for true  {
           fmt.Printf("This loop will run forever.\n");
       }
    }
    

    When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite loop.

    NOTE: You can terminate an infinite loop by pressing Ctrl + C keys.


  • GO FUNCTIONS ↓

    A function is a group of statements that together perform a task. Every Go program has at least one function, which is main(), and all the most trivial programs can define additional functions.

    You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division usually is so each function performs a specific task.

    A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.

    The Go standard library provides numerous built-in functions that your program can call. For example, function len() takes arguments of various types and return the length of the type. For example, if a string is passed to it, it will return length of the string in bytes and if an array is passed to it, it will return the array length as number of elements it have.

    A function is known with various names like a method or a sub-routine or a procedure, etc.

    Defining a Function:

    The general form of a function definition in Go programming language is as follows:

    func function_name( [parameter list] ) [return_types]
    {
       body of the function
    }
    

    A function definition in Go programming language consists of a function header and a function body. Here are all the parts of a function:

    • func func starts the declaration of a function.

    • Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature.

    • Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.

    • Return Type: A function may return a list of values. The return_types is the list of data types of the values the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the not required.

    • Function Body: The function body contains a collection of statements that define what the function does.

    Example:

    Following is the source code for a function called max(). This function takes two parameters num1 and num2 and returns the maximum between the two:

    /* function returning the max between two numbers */
    func max(num1, num2 int) int
    {
       /* local variable declaration */
       result int
    
       if (num1 > num2) {
          result = num1
       } else {
          result = num2
       }
       return result 
    }
    

    Calling a Function:

    While creating a Go function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task.

    When a program calls a function, program control is transferred to the called function. A called function performs defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program.

    To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value. For example:

    package main
    
    import "fmt"
    
    func main() {
       /* local variable definition */
       var a int = 100
       var b int = 200
       var ret int
    
       /* calling a function to get max value */
       ret = max(a, b)
    
       fmt.Printf( "Max value is : %d\n", ret )
    }
    
    /* function returning the max between two numbers */
    func max(num1, num2 int) int {
       /* local variable declaration */
       var result int
    
       if (num1 > num2) {
          result = num1
       } else {
          result = num2
       }
       return result 
    }
    

    I kept max() function along with main() function and compiled the source code. While running final executable, it would produce the following result:

    Max value is : 200
    

    Returning multiple values from Function

    A Go function can return multiple values. For example:

    package main
    
    import "fmt"
    
    func swap(x, y string) (string, string) {
       return y, x
    }
    
    func main() {
       a, b := swap("Mahesh", "Kumar")
       fmt.Println(a, b)
    }
    

    When the above code is compiled and executed, it produces the following result:

    Kumar Mahesh
    

    Function Arguments:

    If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.

    The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.

    While calling a function, there are two ways that arguments can be passed to a function:

    Call TypeDescription
    Call by valueThis method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
    Call by referenceThis method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.

    EXAMPLES

    CALL BY VLAUE

    The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.

    By default, Go programming language uses call by value method to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function. Consider the function swap() definition as follows.

    /* function definition to swap the values */
    func swap(int x, int y) int {
       var temp int
    
       temp = x /* save the value of x */
       x = y    /* put y into x */
       y = temp /* put temp into y */
    
       return temp;
    }
    

    Now, let us call the function swap() by passing actual values as in the following example:

    package main
    
    import "fmt"
    
    func main() {
       /* local variable definition */
       var a int = 100
       var b int = 200
    
       fmt.Printf("Before swap, value of a : %d\n", a )
       fmt.Printf("Before swap, value of b : %d\n", b )
    
       /* calling a function to swap the values */
       swap(a, b)
    
       fmt.Printf("After swap, value of a : %d\n", a )
       fmt.Printf("After swap, value of b : %d\n", b )
    }
    func swap(x, y int) int {
       var temp int
    
       temp = x /* save the value of x */
       x = y    /* put y into x */
       y = temp /* put temp into y */
    
       return temp;
    }
    

    Let us put above code in a single C file, compile and execute it, it will produce the following result:

    Before swap, value of a :100
    Before swap, value of b :200
    After swap, value of a :100
    After swap, value of b :200
    

    Which shows that there is no change in the values though they had been changed inside the function.


    CALL BY REFERENCE

    The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument.

    To pass the value by reference, argument pointers are passed to the functions just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to by its arguments.

    /* function definition to swap the values */
    func swap(x *int, y *int) {
       var temp int
       temp = *x    /* save the value at address x */
       *x = *y      /* put y into x */
       *y = temp    /* put temp into y */
    }
    

    To check the more detail about Go - Pointers, you can check Go - Pointers chapter.

    For now, let us call the function swap() by passing values by reference as in the following example:

    package main
    
    import "fmt"
    
    func main() {
       /* local variable definition */
       var a int = 100
       var b int= 200
    
       fmt.Printf("Before swap, value of a : %d\n", a )
       fmt.Printf("Before swap, value of b : %d\n", b )
    
       /* calling a function to swap the values.
       * &a indicates pointer to a ie. address of variable a and 
       * &b indicates pointer to b ie. address of variable b.
       */
       swap(&a, &b)
    
       fmt.Printf("After swap, value of a : %d\n", a )
       fmt.Printf("After swap, value of b : %d\n", b )
    }
    
    func swap(x *int, y *int) {
       var temp int
       temp = *x    /* save the value at address x */
       *x = *y    /* put y into x */
       *y = temp    /* put temp into y */
    }
    

    Let us put above code in a single C file, compile and execute it, it will produce the following result:

    Before swap, value of a :100
    Before swap, value of b :200
    After swap, value of a :200
    After swap, value of b :100
    

    Which shows that the change has reflected outside of the function as well unlike call by value where changes does not reflect outside of the function.


    By default, Go uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function and above mentioned example while calling max() function used the same method.

    Function Usage:

    Function UsageDescription
    Function as ValueFunctions can be created on the fly and can be used as values.
    Function ClosuresFunctions closure are anonymous functions and can be used in dynamic programming.
    MethodMethod are special functions with a receiver.

    EXAMPLES

    FUNCTION AS VALUES

    Go programming language provides flexibility to create functions on the fly and use them as values. In below example, we've initialized a variable with a function definition. Purpose of this function variable is just to use inbuilt math.sqrt() function. Following is the example:

    package main
    
    import (
       "fmt"
       "math"
    )
    
    func main(){
       /* declare a function variable */
       getSquareRoot := func(x float64) float64 {
          return math.Sqrt(x)
       }
    
       /* use the function */
       fmt.Println(getSquareRoot(9))
    
    }
    

    When the above code is compiled and executed, it produces the following result:

    3
    

    Function Closures

    Go programming language supports anonymous functions which can acts as function closures. Anonymous functions are used when we want to define a function inline without passing any name to it. In our example, we've created a function getSequence() which will return another function. Purpose of this function is to close over a variable i of upper function to form a closure. Following is the example:

    package main
    
    import "fmt"
    
    func getSequence() func() int {
       i:=0
       return func() int {
          i+=1
    	  return i  
       }
    }
    
    func main(){
       /* nextNumber is now a function with i as 0 */
       nextNumber := getSequence()  
    
       /* invoke nextNumber to increase i by 1 and return the same */
       fmt.Println(nextNumber())
       fmt.Println(nextNumber())
       fmt.Println(nextNumber())
       
       /* create a new sequence and see the result, i is 0 again*/
       nextNumber1 := getSequence()  
       fmt.Println(nextNumber1())
       fmt.Println(nextNumber1())
    }
    

    When the above code is compiled and executed, it produces the following result:

    1
    2
    3
    1
    2
    

    Methods

    Go programming language supports special types of functions called methods. In method declaration syntax, a "receiver" is present to represent the container of the function. This receiver can be used to call function using "." operator. Following is the example:

    Syntax

    func (variable_name variable_data_type) function_name() [return_type]{
       /* function body*/
    }
    
    package main
    
    import (
       "fmt"
       "math"
    )
    
    /* define a circle */
    type Circle strut {
       x,y,radius float64
    }
    
    /* define a method for circle */
    func(circle Circle) area() float64 {
       return math.Pi * circle.radius * circle.radius
    }
    
    func main(){
       circle := Circle(x:0, y:0, radius:5)
       fmt.Printf("Circle area: %f", circle.area())
    }
    

    When the above code is compiled and executed, it produces the following result:

    Circle area: 78.539816
    
  • GO ARRAY ↓

    Go programming language provides a data structure called the array, which can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

    Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.

    All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

    Arrays in Go

    Declaring Arrays

    To declare an array in Go, a programmer specifies the type of the elements and the number of elements required by an array as follows:

    var variable_name [SIZE] variable_type
    

    This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid Go data type. For example, to declare a 10-element array called balance of type float32, use this statement:

    var balance [10] float32
    

    Now balance is avariable array which is sufficient to hold upto 10 float numbers.

    Initializing Arrays

    You can initialize array in Go either one by one or using a single statement as follows:

    var balance = [5]float32{1000.0, 2.0, 3.4, 7.0, 50.0}
    

    The number of values between braces { } can not be larger than the number of elements that we declare for the array between square brackets [ ].

    If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write:

    var balance = []float32{1000.0, 2.0, 3.4, 7.0, 50.0}
    

    You will create exactly the same array as you did in the previous example. Following is an example to assign a single element of the array:

    balance[4] = 50.0
    

    The above statement assigns element number 5th in the array with a value of 50.0. All arrays have 0 as the index of their first element which is also called base index and last index of an array will be total size of the array minus 1. Following is the pictorial representation of the same array we discussed above:

    Array Presentation

    Accessing Array Elements

    An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example:

    float32 salary = balance[9]
    

    The above statement will take 10th element from the array and assign the value to salary variable. Following is an example which will use all the above mentioned three concepts viz. declaration, assignment and accessing arrays:

    package main
    
    import "fmt"
    
    func main() {
       var n [10]int /* n is an array of 10 integers */
       var i,j int
    
       /* initialize elements of array n to 0 */         
       for i = 0; i < 10; i++ {
          n[i] = i + 100 /* set element at location i to i + 100 */
       }
    
       /* output each array element's value */
       for j = 0; j < 10; j++ {
          fmt.Printf("Element[%d] = %d\n", j, n[j] )
       }
    }
    

    When the above code is compiled and executed, it produces the following result:

    Element[0] = 100
    Element[1] = 101
    Element[2] = 102
    Element[3] = 103
    Element[4] = 104
    Element[5] = 105
    Element[6] = 106
    Element[7] = 107
    Element[8] = 108
    Element[9] = 109
    

    Go Arrays in Detail

    Arrays are important to C and should need lots of more details. There are following few important concepts related to array which should be clear to a C programmer:

    ConceptDescription
    Multi-dimensional arraysGo supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array.
    Passing arrays to functionsYou can pass to the function a pointer to an array by specifying the array's name without an index.

    MILTI-DIMENSIONAL ARRAYS

    Go programming language allows multidimensional arrays. Here is the general form of a multidimensional array declaration:

    var variable_name [SIZE1][SIZE2]...[SIZEN] variable_type
    

    For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array:

    var threedim [5][10][4]int
    

    Two-Dimensional Arrays:

    The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size x,y you would write something as follows:

    var arrayName [ x ][ y ] variable_type
    

    Where variable_type can be any valid Go data type and arrayName will be a valid Go identifier. A two-dimensional array can be think as a table which will have x number of rows and y number of columns. A 2-dimensional array a, which contains three rows and four columns can be shown as below:

    Two Dimensional Arrays in Go

    Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in a.

    Initializing Two-Dimensional Arrays:

    Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row has 4 columns.

    a = [3][4]int{  
     {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
     {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
     {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
    }
    

    Accessing Two-Dimensional Array Elements:

    An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column index of the array. For example:

    int val = a[2][3]
    

    The above statement will take 4th element from the 3rd row of the array. You can verify it in the above diagram. Let us check below program where we have used nested loop to handle a two dimensional array:

    package main
    
    import "fmt"
    
    func main() {
       /* an array with 5 rows and 2 columns*/
       var a = [5][2]int{ {0,0}, {1,2}, {2,4}, {3,6},{4,8}}
       var i, j int
    
       /* output each array element's value */
       for  i = 0; i < 5; i++ {
          for j = 0; j < 2; j++ {
             fmt.Printf("a[%d][%d] = %d\n", i,j, a[i][j] )
          }
       }
    }
    

    When the above code is compiled and executed, it produces the following result:

    a[0][0]: 0
    a[0][1]: 0
    a[1][0]: 1
    a[1][1]: 2
    a[2][0]: 2
    a[2][1]: 4
    a[3][0]: 3
    a[3][1]: 6
    a[4][0]: 4
    a[4][1]: 8
    

    As explained above, you can have arrays with any number of dimensions, although it is likely that most of the arrays you create will be of one or two dimensions.


    Passing arrays to functions as arguments in Go

    If you want to pass a single-dimension array as an argument in a function, you would have to declare function formal parameter in one of following two ways and all two declaration methods produce similar results because each tells the compiler that an integer array is going to be received. Similar way you can pass multi-dimensional array as formal parameters.

    Way-1

    Formal parameters as a sized array as follows:

    void myFunction(param [10]int)
    {
    .
    .
    .
    }
    

    Way-2

    Formal parameters as an unsized array as follows:

    void myFunction(param []int)
    {
    .
    .
    .
    }
    

    Example

    Now, consider the following function, which will take an array as an argument along with another argument and based on the passed arguments, it will return average of the numbers passed through the array as follows:

    func getAverage(arr []int, int size) float32
    {
       var i int
       var avg, sum float32  
    
       for i = 0; i < size; ++i {
          sum += arr[i]
       }
    
       avg = sum / size
    
       return avg;
    }
    
    

    Now, let us call the above function as follows:

    package main
    
    import "fmt"
    
    func main() {
       /* an int array with 5 elements */
       var  balance = []int {1000, 2, 3, 17, 50}
       var avg float32
    
       /* pass array as an argument */
       avg = getAverage( balance, 5 ) ;
    
       /* output the returned value */
       fmt.Printf( "Average value is: %f ", avg );
    }
    func getAverage(arr []int, size int) float32 {
       var i,sum int
       var avg float32  
    
       for i = 0; i < size;i++ {
          sum += arr[i]
       }
    
       avg = float32(sum / size)
    
       return avg;
    }
    

    When the above code is compiled together and executed, it produces the following result:

    Average value is: 214.400000
    

    As you can see, the length of the array doesn't matter as far as the function is concerned because Go performs no bounds checking for the formal parameters.


  • GO POINTERS ↓

    Pointers in Go are easy and fun to learn. Some Go programming tasks are performed more easily with pointers, and other tasks, such as call by reference, cannot be performed without using pointers. So it becomes necessary to learn pointers to become a perfect Go programmer. Let's start learning them in simple and easy steps.

    As you know, every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory. Consider the following example, which will print the address of the variables defined:

    package main
    
    import "fmt"
    
    func main() {
       var a int = 10   
    
       fmt.Printf("Address of a variable: %x\n", &a  )
    }
    

    When the above code is compiled and executed, it produces result something as follows:

    Address of a variable: 10328000
    

    So you understood what is memory address and how to access it, so base of the concept is over. Now let us see what is a pointer.

    What Are Pointers?

    A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address. The general form of a pointer variable declaration is:

    var var_name *var-type
    

    Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer variable. The asterisk * you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration:

    var ip *int        /* pointer to an integer */
    var fp *float32    /* pointer to a float */
    

    The actual data type of the value of all pointers, whether integer, float, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to.

    How to use Pointers?

    There are few important operations, which we will do with the help of pointers very frequently. (a) we define a pointer variable (b) assign the address of a variable to a pointer and (c) finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. Following example makes use of these operations:

    package main
    
    import "fmt"
    
    func main() {
       var a int= 20   /* actual variable declaration */
       var ip *int        /* pointer variable declaration */
    
       ip = &a  /* store address of a in pointer variable*/
    
       fmt.Printf("Address of a variable: %x\n", &a  )
    
       /* address stored in pointer variable */
       fmt.Printf("Address stored in ip variable: %x\n", ip )
    
       /* access the value using the pointer */
       fmt.Printf("Value of *ip variable: %d\n", *ip )
    }
    

    When the above code is compiled and executed, it produces result something as follows:

    Address of var variable: 10328000
    Address stored in ip variable: 10328000
    Value of *ip variable: 20
    

    nil Pointers in Go

    Go compiler assign a Nil value to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned nil is called a nil pointer.

    The nil pointer is a constant with a value of zero defined in several standard libraries. Consider the following program:

    package main
    
    import "fmt"
    
    func main() {
       var  ptr *int
    
       fmt.Printf("The value of ptr is : %x\n", ptr  )
    }
    

    When the above code is compiled and executed, it produces the following result:

    The value of ptr is 0
    

    On most of the operating systems, programs are not permitted to access memory at address 0 because that memory is reserved by the operating system. However, the memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location. But by convention, if a pointer contains the nil (zero) value, it is assumed to point to nothing.

    To check for a nil pointer you can use an if statement as follows:

    if(ptr != nil)     /* succeeds if p is not nil */
    if(ptr == nil)    /* succeeds if p is null */
    

    Go Pointers in Detail:

    Pointers have many but easy concepts and they are very important to Go programming. There are following few important pointer concepts which should be clear to a Go programmer:

    ConceptDescription
    Go - Array of pointersYou can define arrays to hold a number of pointers.
    Go - Pointer to pointerGo allows you to have pointer on a pointer and so on.
    Passing pointers to functions in GoPassing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function.

    ARRAY OF POINTERS

    Before we understand the concept of arrays of pointers, let us consider the following example, which makes use of an array of 3 integers:

    package main
    
    import "fmt"
     
    const MAX int = 3
     
    func main() {
    
       a := []int{10,100,200}
       var i int
    
       for i = 0; i < MAX; i++ {
          fmt.Printf("Value of a[%d] = %d\n", i, a[i] )
       }
    }
    

    When the above code is compiled and executed, it produces the following result:

    Value of a[0] = 10
    Value of a[1] = 100
    Value of a2] = 200
    

    There may be a situation when we want to maintain an array, which can store pointers to an int or string or any other data type available. Following is the declaration of an array of pointers to an integer:

    var ptr [MAX]*int;
    

    This declares ptr as an array of MAX integer pointers. Thus, each element in ptr, now holds a pointer to an int value. Following example makes use of three integers, which will be stored in an array of pointers as follows:

    package main
    
    import "fmt"
     
    const MAX int = 3
     
    func main() {
       a := []int{10,100,200}
       var i int
       var ptr [MAX]*int;
    
       for  i = 0; i < MAX; i++ {
          ptr[i] = &a[i] /* assign the address of integer. */
       }
    
       for  i = 0; i < MAX; i++ {
          fmt.Printf("Value of a[%d] = %d\n", i,*ptr[i] )
       }
    }
    

    When the above code is compiled and executed, it produces the following result:

    Value of a[0] = 10
    Value of a[1] = 100
    Value of a[2] = 200
    

    Pointer to Pointer Operators

    A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below.

    Pointer to Pointer in Go

    A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional asterisk in front of its name. For example, following is the declaration to declare a pointer to a pointer of type int:

    var ptr **int;
    

    When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the asterisk operator be applied twice, as is shown below in the example:

    package main
    
    import "fmt"
    
    func main() {
    
       var a int
       var ptr *int
       var pptr **int
    
       a = 3000
    
       /* take the address of var */
       ptr = &a
    
       /* take the address of ptr using address of operator & */
       pptr = &ptr
    
       /* take the value using pptr */
       fmt.Printf("Value of a = %d\n", a )
       fmt.Printf("Value available at *ptr = %d\n", *ptr )
       fmt.Printf("Value available at **pptr = %d\n", **pptr)
    }
    

    When the above code is compiled and executed, it produces the following result:

    Value of var = 3000
    Value available at *ptr = 3000
    Value available at **pptr = 3000
    

    Passing pointers to functions

    Go programming language allows you to pass a pointer to a function. To do so, simply declare the function parameter as a pointer type.

    Following a simple example where we passed two pointers to a function and change the value inside the function which reflects back in the calling function:

    package main
    
    import "fmt"
    
    func main() {
       /* local variable definition */
       var a int = 100
       var b int= 200
    
       fmt.Printf("Before swap, value of a : %d\n", a )
       fmt.Printf("Before swap, value of b : %d\n", b )
    
       /* calling a function to swap the values.
       * &a indicates pointer to a ie. address of variable a and 
       * &b indicates pointer to b ie. address of variable b.
       */
       swap(&a, &b);
    
       fmt.Printf("After swap, value of a : %d\n", a )
       fmt.Printf("After swap, value of b : %d\n", b )
    }
    
    func swap(x *int, y *int) {
       var temp int
       temp = *x    /* save the value at address x */
       *x = *y      /* put y into x */
       *y = temp    /* put temp into y */
    }
    

    When the above code is compiled and executed, it produces the following result:

    Before swap, value of a :100
    Before swap, value of b :200
    After swap, value of a :200
    After swap, value of b :100
    
  • GO STRUCTURE ↓

    Go arrays allow you to define type of variables that can hold several data items of the same kind but structure is another user defined data type available in Go programming, which allows you to combine data items of different kinds.

    Structures are used to represent a record, Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book:

    • Title

    • Author

    • Subject

    • Book ID

    Defining a Structure

    To define a structure, you must use type and struct statements. The struct statement defines a new data type, with more than one member for your program. type statement binds a name with the type which is struct in our case. The format of the struct statement is this:

    type struct_variable_type struct {
       member definition;
       member definition;
       ...
       member definition;
    }
    

    Once a structure type is defined, it can be used to declare variables of that type using following syntax.

    variable_name := structure_variable_type {value1, value2...valuen}
    

    Accessing Structure Members

    To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type. Following is the example to explain usage of structure:

    package main
    
    import "fmt"
    
    type Books struct {
       title string
       author string
       subject string
       book_id int
    }
    
    func main() {
       var Book1 Books        /* Declare Book1 of type Book */
       var Book2 Books        /* Declare Book2 of type Book */
     
       /* book 1 specification */
       Book1.title = "Go Programming"
       Book1.author = "Mahesh Kumar"
       Book1.subject = "Go Programming Tutorial"
       Book1.book_id = 6495407
    
       /* book 2 specification */
       Book2.title = "Telecom Billing"
       Book2.author = "Zara Ali"
       Book2.subject = "Telecom Billing Tutorial"
       Book2.book_id = 6495700
     
       /* print Book1 info */
       fmt.Printf( "Book 1 title : %s\n", Book1.title)
       fmt.Printf( "Book 1 author : %s\n", Book1.author)
       fmt.Printf( "Book 1 subject : %s\n", Book1.subject)
       fmt.Printf( "Book 1 book_id : %d\n", Book1.book_id)
    
       /* print Book2 info */
       fmt.Printf( "Book 2 title : %s\n", Book2.title)
       fmt.Printf( "Book 2 author : %s\n", Book2.author)
       fmt.Printf( "Book 2 subject : %s\n", Book2.subject)
       fmt.Printf( "Book 2 book_id : %d\n", Book2.book_id)
    }
    

    When the above code is compiled and executed, it produces the following result:

    Book 1 title : Go Programming
    Book 1 author : Mahesh Kumar
    Book 1 subject : Go Programming Tutorial
    Book 1 book_id : 6495407
    Book 2 title : Telecom Billing
    Book 2 author : Zara Ali
    Book 2 subject : Telecom Billing Tutorial
    Book 2 book_id : 6495700
    

    Structures as Function Arguments

    You can pass a structure as a function argument in very similar way as you pass any other variable or pointer. You would access structure variables in the similar way as you have accessed in the above example:

    package main
    
    import "fmt"
    
    type Books struct {
       title string
       author string
       subject string
       book_id int
    }
    
    func main() {
       var Book1 Books        /* Declare Book1 of type Book */
       var Book2 Books        /* Declare Book2 of type Book */
     
       /* book 1 specification */
       Book1.title = "Go Programming"
       Book1.author = "Mahesh Kumar"
       Book1.subject = "Go Programming Tutorial"
       Book1.book_id = 6495407
    
       /* book 2 specification */
       Book2.title = "Telecom Billing"
       Book2.author = "Zara Ali"
       Book2.subject = "Telecom Billing Tutorial"
       Book2.book_id = 6495700
     
       /* print Book1 info */
       printBook(Book1)
    
       /* print Book2 info */
       printBook(Book2)
    }
    func printBook( book Books )
    {
       fmt.Printf( "Book title : %s\n", book.title);
       fmt.Printf( "Book author : %s\n", book.author);
       fmt.Printf( "Book subject : %s\n", book.subject);
       fmt.Printf( "Book book_id : %d\n", book.book_id);
    }
    

    When the above code is compiled and executed, it produces the following result:

    Book title : Go Programming
    Book author : Mahesh Kumar
    Book subject : Go Programming Tutorial
    Book book_id : 6495407
    Book title : Telecom Billing
    Book author : Zara Ali
    Book subject : Telecom Billing Tutorial
    Book book_id : 6495700
    

    Pointers to Structures

    You can define pointers to structures in very similar way as you define pointer to any other variable as follows:

    var struct_pointer *Books
    

    Now, you can store the address of a structure variable in the above defined pointer variable. To find the address of a structure variable, place the & operator before the structure's name as follows:

    struct_pointer = &Book1;
    

    To access the members of a structure using a pointer to that structure, you must use the "." operator as follows:

    struct_pointer.title;
    

    Let us re-write above example using structure pointer, hope this will be easy for you to understand the concept:

    package main
    
    import "fmt"
    
    type Books struct {
       title string
       author string
       subject string
       book_id int
    }
    
    func main() {
       var Book1 Books        /* Declare Book1 of type Book */
       var Book2 Books        /* Declare Book2 of type Book */
     
       /* book 1 specification */
       Book1.title = "Go Programming"
       Book1.author = "Mahesh Kumar"
       Book1.subject = "Go Programming Tutorial"
       Book1.book_id = 6495407
    
       /* book 2 specification */
       Book2.title = "Telecom Billing"
       Book2.author = "Zara Ali"
       Book2.subject = "Telecom Billing Tutorial"
       Book2.book_id = 6495700
     
       /* print Book1 info */
       printBook(&Book1)
    
       /* print Book2 info */
       printBook(&Book2)
    }
    func printBook( book *Books )
    {
       fmt.Printf( "Book title : %s\n", book.title);
       fmt.Printf( "Book author : %s\n", book.author);
       fmt.Printf( "Book subject : %s\n", book.subject);
       fmt.Printf( "Book book_id : %d\n", book.book_id);
    }
    

    When the above code is compiled and executed, it produces the following result:

    Book title : Go Programming
    Book author : Mahesh Kumar
    Book subject : Go Programming Tutorial
    Book book_id : 6495407
    Book title : Telecom Billing
    Book author : Zara Ali
    Book subject : Telecom Billing Tutorial
    Book book_id : 6495700
    
  • GO RANGE AND MAPS ↓

    GO RANGE

    The range keyword is used in for loop to iterate over items of an array, slice, channel or map. With array and slices, it returns the index of the item as integer. With maps, it returns the key of the next key-value pair. Range either returns one value or two. If only one value is used on the left of a range expression, it is the 1st value in the following table.

    Range expression1st Value2nd Value(Optional)
    Array or slice a [n]Eindex i inta[i] E
    String s string typeindex i intrune int
    map m map[K]Vkey k Kvalue m[k] V
    channel c chan Eelement e Enone

    Example

    Following is the example:

    package main
    
    import "fmt"
    
    func main() {
       /* create a slice */
       numbers := []int{0,1,2,3,4,5,6,7,8} 
       
       /* print the numbers */
       for i:= range numbers {
          fmt.Println("Slice item",i,"is",numbers[i])
       }
       
       /* create a map*/
       coutryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo"}
       
       /* print map using keys*/
       for country := range countryCapitalMap {
          fmt.Println("Capital of",country,"is",countryCapitalMap[country])
       }
       
       /* print map using key-value*/
       for country,capital := range countryCapitalMap {
          fmt.Println("Capital of",country,"is",capital)
       }
    }
    

    When the above code is compiled and executed, it produces the following result:

    Slice item 0 is 0
    Slice item 1 is 1
    Slice item 2 is 2
    Slice item 3 is 3
    Slice item 4 is 4
    Slice item 5 is 5
    Slice item 6 is 6
    Slice item 7 is 7
    Slice item 8 is 8
    Capital of France is Paris
    Capital of Italy is Rome
    Capital of Japan is Tokyo
    Capital of France is Paris
    Capital of Italy is Rome
    Capital of Japan is Tokyo
    

    GO MAPS

    Go provides another important data type map which maps unique keys to values. A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can strore the value in a Map object. After value is stored, you can retrieve it by using its key.

    Defining a map

    You must use make function to create a map.

    /* declare a variable, by default map will be nil*/
    var map_variable map[key_data_type]value_data_type
    
    /* define the map as nil map can not be assigned any value*/
    map_variable = make(map[key_data_type]value_data_type)
    

    Example

    Following example illustrates creation and usage of map.

    package main
    
    import "fmt"
    
    func main() {
       var countryCapitalMap map[string]string
       /* create a map*/
       countryCapitalMap = make(map[string]string)
       
       /* insert key-value pairs in the map*/
       countryCapitalMap["France"] = "Paris"
       countryCapitalMap["Italy"] = "Rome"
       countryCapitalMap["Japan"] = "Tokyo"
       countryCapitalMap["India"] = "New Delhi"
       
       /* print map using keys*/
       for country := range countryCapitalMap {
          fmt.Println("Capital of",country,"is",countryCapitalMap[country])
       }
       
       /* test if entry is present in the map or not*/
       capital, ok := countryCapitalMap["United States"]
       /* if ok is true, entry is present otherwise entry is absent*/
       if(ok){
          fmt.Println("Capital of United States is", capital)  
       }else {
          fmt.Println("Capital of United States is not present") 
       }
    }
    

    When the above code is compiled and executed, it produces the following result:

    Capital of India is New Delhi
    Capital of France is Paris
    Capital of Italy is Rome
    Capital of Japan is Tokyo
    Capital of United States is not present
    

    delete() function

    delete() function is used to delete an entry from the map. It requires map and corresponding key which is to be deleted. Following is the example:

    package main
    
    import "fmt"
    
    func main() {   
       /* create a map*/
       countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo","India":"New Delhi"}
       
       fmt.Println("Original map")   
       
       /* print map */
       for country := range countryCapitalMap {
          fmt.Println("Capital of",country,"is",countryCapitalMap[country])
       }
       
       /* delete an entry */
       delete(countryCapitalMap,"France");
       fmt.Println("Entry for France is deleted")  
       
       fmt.Println("Updated map")   
       
       /* print map */
       for country := range countryCapitalMap {
          fmt.Println("Capital of",country,"is",countryCapitalMap[country])
       }
    }
    

    When the above code is compiled and executed, it produces the following result:

    Original Map
    Capital of France is Paris
    Capital of Italy is Rome
    Capital of Japan is Tokyo
    Capital of India is New Delhi
    Entry for France is deleted
    Updated Map
    Capital of India is New Delhi
    Capital of Italy is Rome
    Capital of Japan is Tokyo
    

  • GO RECURSION, TYPE CASTING & INTERFACE ↓

    Recursion is the process of repeating items in a self-similar way. Same applies in programming languages as well where if a programming allows you to call a function inside the same function that is called recursive call of the function as follows.

    func recursion() {
       recursion() /* function calls itself */
    }
    
    func main() {
       recursion()
    }
    

    The Go programming language supports recursion, i.e., a function to call itself. But while using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go in infinite loop.

    Recursive function are very useful to solve many mathematical problems like to calculate factorial of a number, generating Fibonacci series, etc.

    Number Factorial

    Following is an example, which calculates factorial for a given number using a recursive function:

    package main
    
    import "fmt"
    
    func factorial(i int) {
       if(i <= 1) {
          return 1
       }
       return i * factorial(i - 1)
    }
    
    func main() {  
        var i int = 15
        fmt.Printf("Factorial of %d is %d\n", i, factorial(i))
    }
    

    When the above code is compiled and executed, it produces the following result:

    Factorial of 15 is 2004310016
    

    Fibonacci Series

    Following is another example, which generates Fibonacci series for a given number using a recursive function:

    package main
    
    import "fmt"
    
    func fibonaci(i int) {
       if(i == 0) {
          return 0
       }
       if(i == 1) {
          return 1
       }
       return fibonaci(i-1) + fibonaci(i-2)
    }
    
    func main() {
        var i int
        for i = 0; i < 10; i++ {
           fmt.Printf("%d\t%n", fibonaci(i))
        }    
    }
    

    When the above code is compiled and executed, it produces the following result:

    0	1	1	2	3	5	8	13	21	34
    

    Type casting is a way to convert a variable from one data type to another data type. For example, if you want to store a long value into a simple integer then you can type cast long to int. You can convert values from one type to another using the cast operator as following:

    type_name(expression)
    

    Example

    Consider the following example where the cast operator causes the divison of one integer variable by another to be performed as a floating number operation.

    package main
    
    import "fmt"
    
    func main() {
       var sum int = 17
       var count int = 5
       var mean float32
       
       maen = float32(sum)/float32(count)
       fmt.Printf("Value of mean : %f\n",mean)
    }
    

    When the above code is compiled and executed, it produces the following result:

    Value of mean : 3.400000
    

    Go programming provides another data type called interfaces which represents a set of method signatures. struct data type implements these interfaces to have metho definitions for the method signature of the interfaces.

    Syntax

    /* define an interface */
    type interface_name interface {
       method_name1 [return_type]
       method_name2 [return_type]
       method_name3 [return_type]
       ...
       method_namen [return_type]
    }
    
    /* define a struct */
    type struct_name struct {
       /* variables */
    }
    
    /* implement interface methods*/
    func (struct_name_variable struct_name) method_name1() [return_type] {
       /* method implementation */
    }
    ...
    func (struct_name_variable struct_name) method_namen() [return_type] {
       /* method implementation */
    }
    

    Example

    package main
    
    import (
       "fmt"
       "math"
    )
    
    /* define an interface */
    type Shape interface {
       area() float64
    }
    
    /* define a circle */
    type Circle struct {
       x,y,radius float64
    }
    
    /* define a rectangle */
    type Rectangle struct {
       width, height float64
    }
    
    /* define a method for circle (implementation of Shape.area())*/
    func(circle Circle) area() float64 {
       return math.Pi * circle.radius * circle.radius
    }
    
    /* define a method for rectangle (implementation of Shape.area())*/
    func(rect Rectangle) area() float64 {
       return rect.width * rect.height
    }
    
    /* define a method for shape */
    func getArea(shape Shape) float64 {
       return shape.area()
    }
    
    func main() {
       circle := Circle{x:0,y:0,radius:5}
       rectangle := Rectangle {width:10, height:5}
       
       fmt.Printf("Circle area: %f\n",getArea(circle))
       fmt.Printf("Rectangle area: %f\n",getArea(rectangle))
    }
    
    

    When the above code is compiled and executed, it produces the following result:

    Circle area: 78.539816
    Rectangle area: 50.000000