Home > Articles > Programming

Learning a New Programming Language: My Experience with Go

Go programmer Siddhartha Singh explains what makes Go different and when you should consider using it. Using examples of successful Go programs, he shows how easily you can set up the Go environment, build programs, and run them. Rather than just focusing on the syntax, learn the important motivating factors for considering Go as your language of choice.
Like this article? We recommend

Go programmer Siddhartha Singh explains what makes Go different and when you should consider using it. Using examples of successful Go programs, he shows how easily you can set up the Go environment, build programs, and run them. Rather than just focusing on the syntax, learn the important motivating factors for considering Go as your language of choice.

Getting Ready to 'Go'

Invented at Google, Go was created by the makers of UNIX. The first thing you need to know about Go is that it compiles to machine code. What does this mean? It's ready to replace other compiled languages such as C/C++.

To get started using Go, download the Go distribution. To write Go code, you can use command-line tools, or you can download golangide, an open source IDE written in C++. If you know Eclipse, try the Go plug-in GoClipse.

One very nice feature of Go is its documentation. For example, suppose you run a command like this:

godoc -http=:8081

This will run a web server locally on port 8081. Then type this in your browser:

http://localhost:8081

The documentation for the command is displayed in your browser.

To see help on running the go command, for example, run this:

go --h

To be able to build local programs and packages, the go tool has three requirements:

  • The Go bin directory ($GOROOT/bin or %GOROOT%\bin) must be in the path.
  • There must be a directory tree with a src directory where the source code for the local programs and packages resides. For example, if you create a directory go under HOME, create a file as ~/go/src/HelloWorld.go, and so on.
  • The directory above the src directory must be in the GOPATH environment variable. For example, to build the HelloWorld example I just mentioned by using the go tool, do this:
  • $ export GOPATH=$HOME/go
    $ cd $GOPATH/src
    $ go build
  • In both cases, we assume that PATH includes $GOROOT/bin or %GOROOT%\bin. Once the go tool has built the program, you can run it. By default, the executable is given the same name as the directory in which it resides; for example, HelloWorld on UNIX-like systems and HelloWorld.exe on Windows. Once the program is built, we can run it in the usual way:
  • $ ./HelloWorld
     Hello World!

A 'Hello World' Program in Go

It's a tradition to start with a Hello World program, so here it is, probably the shortest working Go program you can have:

file : HelloWorld.go

package main

import "fmt"

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

From a command line (terminal in Linux), you run it like this:

$ go run HelloWorld.go

This command both compiles and runs the program.

Now coming back on track. What factors might cause you to switch to writing in a different programming language? Would it be management's decision, or your own? Several factors motivated me, as described in the following section.

What Motivated Me to Learn Go?

What Motivated Me to Learn Go?

Languages are designed keeping a particular domain in mind, which means one particular language won't fit for all needs. For instance, C/C++ are for systems and/or performance-related programs. PHP is good for building web pages. Java provides platform independence. Similarly, Go is designed for maintaining flexibility when programming for the latest technologies, as well as for writing system programs. Let's examine some of the unique features of Go that help programmers to write scalable, distributed, parallel programs easily—without worrying about installing separate libraries.

Factor 1: Pointers

Pointers have always fascinated me while writing performance-oriented programs in C/C++. With pointers, you know exactly about memory layouts. Go gives the programmer control over which data structure is a pointer and which isn't.

Pointers are important for performance and indispensable if you want to do systems programming, close to the operating system and network. Here's a code sample that shows the usage of pointers:

//file pointer.go
package main

import "fmt"

func main() {
      var i1 = 5
      fmt.Printf("An integer: %d, its location in memory: %p\n", i1, &i1)
      var intP *int
      intP = &i1
      fmt.Printf("The value at memory location %p is %d\n", intP, *intP)
}

Like most other low-level (system) languages, such as C, C++, and D, Go has the concept of pointers. But pointer arithmetic (such as pointer + 2 to go through the bytes of a string or the positions in an array) often leads to erroneous memory access in C, and therefore to fatal program crashes. Go doesn't allow pointer arithmetic, which makes the language memory-safe. Go pointers more resemble the references from languages like Java, C#, and Visual Basic.NET. For example, the following is invalid Go code:

c = *p++

A pointed variable also persists in memory for as long as at least one pointer points to it, which means that the pointer's lifetime is independent of the scope in which it was created. Think of a smart pointer class in C++, which is implemented using reference counting methodology.

Factor 2: Object-Oriented Programming (OOP)

Go is an OO language, but not in the traditional sense, because it doesn't have the concept of classes and inheritance. However, it supports the concept of interfaces, with which a lot of aspects of object orientation can be made available.

An interface defines a set of methods that are abstracts (pure virtual in C++), but these methods don't contain code; that is, they're not implemented. Also, an interface cannot contain variables, and therefore has no context.

The prototype of an interface is as follows:

type Namer interface {
Method1(param_list) return_type
Method2(param_list) return_type
...
}

where Namer is an interface type.

Three important aspects of OO languages are encapsulation, inheritance, and polymorphism. How are these aspects envisioned in Go?

  1. Encapsulation (data hiding): In contrast to other OO languages with four or more access levels, Go simplifies to only two:
    1. Package scope: "object" is only known in its own package if it starts with a lowercase letter.
    2. Exported: "object" is visible outside of its package if it starts with an uppercase letter.
    3. A type can only have methods defined in its own package.

  2. Inheritance: By composition; that is, embedding of one or more types (I discuss types later in this article) with the desired behavior (fields and methods). Multiple inheritance is possible through embedding multiple types.
  3. Polymorphism: By interfaces; that is, a variable of a type can be assigned to a variable of any interface it implements. Types and interfaces are loosely coupled; again, multiple inheritance is possible through implementing multiple interfaces. Go's interfaces are not a variant of Java or C# interfaces. They're independent; in other words, they don't know anything about their hierarchy.

How does this work? Let's say you want to implement an "object serializer" to write to different kinds of stream (say, to a file and a network). In languages like Java, you declare different interfaces to it and implement them in a class containing data. For example, in Java:

//File streamer interface
interface IFileStreamer
{
  void StreamToFile();
}

//Network streamer interface
interface INetworkStreamer
{
  void StreamToNetwork();
}

// A class StreamWriter to implement these interfaces
public class StreamWriter implements
IFileStreamer, INetworkStreamer
{
    private String[] mBuf;
    public void StreamToFile()
     {}
    public void StreamToNetwork()
     {}
}

In Go, this will be implemented as described below:

//Go Step 1: Define your data structures
type ByteStream struct {
  mBuffer string
}
//Go Step 2: Define an interface that could use the data structure we have
//File streamer interface
type IFileStreamer interface {
    StreamToFile()
}
//Network streamer interface
type INetworkStreamer interface {
    StreamToNetwork()
}
//Go Step 3: Implement methods to work on data
func (byteStream ByteStream) StreamToFile()  {
    WriteToFile(byteStream.mBuffer);
}

func (byteStream ByteStream) StreamToNetwork() {
  WriteToNetwork(byteStream.mBuffer);
}

If you look carefully, it appears to be data-centric; that is, define your data first and build your interface abstractions. Here, hierarchy is kind of built "along the way," without explicitly stating it; depending on the method signatures associated with the type, it's understood as implementing specific interfaces.

To this point, it might seem that there isn't much difference. But wait: Consider a case where you get a requirement to add one more stream, called a memory stream. In the case of Java, you would have to declare another interface and implement it in the class. That is, you would have to touch the existing class:

interface IMemoryStreamer
{
  void StreamToMemory();
}

public class StreamWriter implements
IFileStreamer, INetworkStreamer, IMemoryStreamer
{
...
//Implement the new function
      void StreamToMemory()
      {}
}

Here comes the benefit of Go: You don't have to change the data class. Just write one more function with the type ByteStream:

func (byteStream ByteStream) StreamToMemory()  {
    WriteToMemory(byteStream.mBuffer);
}

This is a shift in the concept of traditional object orientation.

Factor 3: Built-in Concurrency Support

Go adheres to a paradigm known as Communicating Sequential Processes (CSP, invented by C.A.R. Hoare), also called the message, which is already available in Erlang. To execute tasks in parallel, you have to write "Go routines."

Goroutines

Asynchronous function call. Just prefix the function call with the word go. No prior knowledge is required at the time of function declaration. Return values, if any, will be discarded. No way exists to kill spawned goroutines. However, they are all killed when main() exits.

Channels

Go uses channels to synchronize goroutines. A channel is type-safe duplex FIFO, synchronized across goroutines. The syntax looks like this:

<- chn to read; chn <- to write

It reads/writes blocks until the data (command) is available.

Select Statements

Like a switch, except it's for channel I/O. It picks up one ready channel I/O operation from several ready/blocked operations. Non-blocking I/O is possible using the default: option. For example:

package main
import (
  "fmt"
  "math/rand"
  "time"
)
func consumer(c1, c2 chan int) {
  timeout := time.After(time.Second*5)
for {
    var i int
    select {
    case i = <-c1:
      fmt.Println("Producer 1 yielded", i)
    case i = <-c2:
      fmt.Println("Producer 2 yielded", i)
    case <- timeout:
      return
    default:
      time.Sleep(time.Second)
    }
  }
}

func producer(c chan int) {
 for i := 0; i < 10; i++ {
c <- rand.Int()
}
}

func main() {
c1, c2 := make(chan int), make(chan int)
 go producer(c1) // go routine, prefix 'go'
 go producer(c2) // go routine, prefix 'go'
 consumer(c1, c2)
}

Factor 4: Garbage Collection

Oh! So no memory leaks! Great!! The Go developer doesn't have to code to release the memory for variables and structures that are not used in the program. A separate process in the Go runtime, the garbage collector, takes care of that problem: It searches for variables that are not listed anymore and frees that memory.

Functionality for this process can be accessed via the runtime package. Garbage collection can be called explicitly by invoking the function runtime.GC(), but this is only useful in rare cases, such as when memory resources are scarce, a large chunk of memory could immediately be freed at that point in the execution, and the program takes only a momentary decrease in performance (for the garbage collection-process).

Factor 5: Error Handling Through Multiple Return Values

Go has no exception mechanism, like the try/catch in Java or .NET; you cannot throw exceptions. Instead it has a defer, panic, and recover mechanism.

There are two primary paradigms today in native languages for handling errors: return codes, as in C, or exceptions, as in OO alternatives. Of the two, return codes are the more frustrating option, because returning error codes often conflicts with returning other data from the function. Go solves this problem by allowing functions to return multiple values. One value returned is of type error and can be checked anytime a function returns. If you don't care about the error value, you don't check it. In either case, the regular return values of the function are available to you.

Factor 6: Web Programming

In today's world, we need help from a language to write web-based programs. The trend is to write APIs that are REST-based.

HTML Templates

Go has extremely good and safe support for HTML templates, which are data-driven and make templates suitable for web programming. The package template (html/template) is used for generating HTML output that's safe against code injection.

Writing a Standalone Web Server

It's easy to write a web server in Go:

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hurray, how good is : %s!", r.URL.Path[1:])
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8000", nil)
}

When you run this program and type the URL in your browser,

http://localhost:8000/Go

you should see this response:

Hurray, how good is : Go!
Conclusion

Conclusion

I think this one article has been sufficient to give you a feeling of how Go works. Many other features are also available—expandable arrays, hash maps, etc., make Go extremely good for writing programs. Enjoy them as you get ready to "go"!

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020