DEV Community

Cover image for Introduction to GO Programming

Introduction to GO Programming

Table of Contents

  1. Introduction
  2. Why is it Awesome
  3. Popular Use cases
  4. Tools Built Using Go
  5. Go Software
  6. Enable dependency tracking for your code
  7. Create a module
  8. Call your code from another module
  9. Return and handle an error
  10. Go vs other languages

Introduction :

  • Go is an open-source programming language developed by Google
  • It was designed at Google in 2007 by Robert Griesemer,and Ken Thompson, and publicly announced in November 2009.
  • It is syntactically similar to C, but also has garbage collection, structural typing
  • It is often referred to as Golang to avoid ambiguity and because of its former domain name, golang.org, but its proper name is Go
  • the gopher : The Go gopher was created by renowned illustrator Renee French. It has become a beloved mascot for the Go brand. The Gopher is a reminder of the approachability and fun that comes with the Go brand and language.

Why is it Awesome

  1. Focus on simplicity,clarity & scalability

    • Inspired by languages like python
    • Aims to provide a clean, understandable syntax
  2. High performance & Focus on Concurrency

    • Similar to C or C++
    • Popular for tasks that benefit from multi-threading
  3. Batteries included

    • Go comes with a standard library
    • Many core features are built-included
  4. Static typing

    • Go is a type-safe language
    • Allows you to catch many errors early

Popular Use cases

1.Networking & APIs
2.Microservices
3.CLI Tools

Tools Built Using Go

  1. Docker - Containerization platform
  2. Kubernetes - Container orchestration system
  3. Terraform - Infrastructure as Code tool
  4. Prometheus - Monitoring and alerting toolkit
  5. Hugo - Static site generator
  6. CockroachDB - Distributed SQL database
  7. Traefik - Cloud-native edge router
  8. Etcd - Distributed key-value store
  9. Caddy - Web server
  10. Syncthing - Continuous file synchronization
  • These applications leverage Go's performance, concurrency, and simplicity.

Go Software

  • Go to the go website and then click on the download button

  • Go can be installed in multiple Operating systems and information given below

  • Its a straight forward installation, just keep click next to complete the installation.

Enable dependency tracking for your code

  • When your code imports packages contained in other modules, you manage those dependencies through your code's own module.
  • That module is defined by a go.mod file that tracks the modules that provide those packages. That go.mod file stays with your code, including in your source code repository.
  • To enable dependency tracking for your code by creating a go.mod file, run the go mod init command, giving it the name of the module your code will be in. The name is the module's module path.

  • Try the below command in the software folder

    go mod init example/hello

_ go: creating new go.mod: module example/hello_

  • Create a file hello.go file
package main

import "fmt"

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

Enter fullscreen mode Exit fullscreen mode
  • Run your code to see the greeting by running the command go run . or go run hello.go > Hello, World!

Create a module

  1. Create a module -- Write a small module with functions you can call from another module.

1.1 Open a command prompt and cd to your home directory.

On Linux or Mac:

cd
On Windows:

cd %HOMEPATH%
Enter fullscreen mode Exit fullscreen mode

1.2 Create a greetings directory for your Go module source code.

  • For example, from your home directory use the following commands:
    mkdir greetings
    cd greetings
    

1.3 Start your module using the go mod init command

Run the go mod init command, giving it your module path -- here, use example.com/greetings

$ go mod init example.com/greetings
go: creating new go.mod: module example.com/greetings
Enter fullscreen mode Exit fullscreen mode
  • The go mod init command creates a go.mod file to track your code's dependencies

1.4 create a file greetings.go

1.5 Paste below code into greetings.go file

package greetings

import "fmt"

// Hello returns a greeting for the named person.
func Hello(name string) string {
    // Return a greeting that embeds the name in a message.
    message := fmt.Sprintf("Hi, %v. Welcome!", name)
    return message
}

Enter fullscreen mode Exit fullscreen mode

1.6 Implement a Hello function to return the greeting

1.7 In Go, the := operator is a shortcut for declaring and initializing a variable in one line (Go uses the value on the right to determine the variable's type). Taking the long way, you might have written this as:

var message string
message = fmt.Sprintf("Hi, %v. Welcome!", name)
Enter fullscreen mode Exit fullscreen mode

Call your code from another module

1.Create a hello directory for your source code main folder. This is where you'll write your caller.

  • After you create the folder and its looks like this
<home>/
 |-- greetings/
 |-- hello/
Enter fullscreen mode Exit fullscreen mode

2.For example, if your command prompt is in the greetings directory, you could use the following commands:

cd ..
mkdir hello
cd hello
Enter fullscreen mode Exit fullscreen mode

3.Enable dependency tracking for the code you're about to write

$ go mod init example.com/hello
go: creating new go.mod: module example.com/hello
Enter fullscreen mode Exit fullscreen mode

4.In your text editor, in the hello directory, create a file in which to write your code and call it hello.go.

  • Write code to call the Hello function, then print the function's return value
  • Paste the below code in hello.go file
package main

import (
    "fmt"

    "example.com/greetings"
)

func main() {
    // Get a greeting message and print it.
    message := greetings.Hello("Gladys")
    fmt.Println(message)
}
Enter fullscreen mode Exit fullscreen mode
  • In the above code declared a main package. In Go, code executed as an application must be in a main package.

  • Import two packages: example.com/greetings and the fmt package.

  • Get a greeting by calling the greetings package’s Hello function.

5.Edit the example.com/hello module to use your local example.com/greetings module

  • To do that, use the go mod edit command to edit the example.com/hello module to redirect Go tools from its module path

  • From the command prompt in the hello directory, run the following command

$ go mod edit -replace example.com/greetings=../greetings
Enter fullscreen mode Exit fullscreen mode
  • The command specifies that example.com/greetings should be replaced with ../greetings for the purpose of locating the dependency

  • go.mod file will small changes with replace command at the bottom

module example.com/hello

go 1.16

replace example.com/greetings => ../greetings
Enter fullscreen mode Exit fullscreen mode
  • From the command prompt in the hello directory, run the go mod tidy command to synchronize the example.com/hello module's dependencies, adding those required by the code, but not yet tracked in the module.
$ go mod tidy
go: found example.com/greetings in example.com/greetings v0.0.0-00010101000000-000000000000
Enter fullscreen mode Exit fullscreen mode
  • After running the above code and go.mod looks like below
module example.com/hello

go 1.16

replace example.com/greetings => ../greetings

require example.com/greetings v0.0.0-00010101000000-000000000000
Enter fullscreen mode Exit fullscreen mode
  • The command found the local code in the greetings directory, then added a require directive to specify that example.com/hello requires example.com/greetings.
  • You created this dependency when you imported the greetings package in hello.go.

  • At the command prompt in the hello directory, run your code to confirm that it works.

$ go run .
Hi, Gladys. Welcome!
Enter fullscreen mode Exit fullscreen mode

Return and handle an error

  • Handling errors is an essential feature of solid code. In this section, you'll add a bit of code to return an error from the greetings module, then handle it in the caller.
  • Refer Section 4 & 5

1.In greetings/greetings.go, add the code highlighted below

  • There's no sense sending a greeting back if you don't know who to greet. Return an error to the caller if the name is empty.
package greetings

import (
    "errors"
    "fmt"
)

// Hello returns a greeting for the named person.
func Hello(name string) (string, error) {
    // If no name was given, return an error with a message.
    if name == "" {
        return "", errors.New("empty name")
    }

    // If a name was received, return a value that embeds the name
    // in a greeting message.
    message := fmt.Sprintf("Hi, %v. Welcome!", name)
    return message, nil
}
Enter fullscreen mode Exit fullscreen mode

In this code, you:

  • Change the function so that it returns two values: a string and an error.
  • Your caller will check the second value to see if an error occurred.
  • Import the Go standard library *errors * package so you can use its errors.New function.
  • Add an if statement to check for an invalid request (an empty string where the name should be) and return an error if the request is invalid. The errors.New function returns an error with your message inside.
  • Add nil (meaning no error) as a second value in the successful return. That way, the caller can see that the function succeeded.

2.In your hello/hello.go file, handle the error now returned by the Hello function, along with the non-error value

  • Paste the below code in hello.go
package main

import (
    "fmt"
    "log"

    "example.com/greetings"
)

func main() {
    // Set properties of the predefined Logger, including
    // the log entry prefix and a flag to disable printing
    // the time, source file, and line number.
    log.SetPrefix("greetings: ")
    log.SetFlags(0)

    // Request a greeting message.
    message, err := greetings.Hello("")
    // If an error was returned, print it to the console and
    // exit the program.
    if err != nil {
        log.Fatal(err)
    }

    // If no error was returned, print the returned message
    // to the console.
    fmt.Println(message)
}
Enter fullscreen mode Exit fullscreen mode
  • Configure the log package
  • Assign both of the Hello return values, including the error, to variables.
  • Change the Hello argument from Gladys’s name to an empty string, so you can try out your error-handling code.

3.At the command line in the hello directory, run hello.go to confirm that the code works.

$ go run .
greetings: empty name
exit status 1
Enter fullscreen mode Exit fullscreen mode

Go vs Other languages

  • Go (Golang) Benefits Compared to Other Languages:
  1. Simplicity:

    • Go: Clean, minimal syntax makes code easy to read and maintain.
    • Others: Languages like Java or C++ have more complex syntax and features.
  2. Concurrency:

    • Go: Native support with goroutines and channels simplifies concurrent programming.
    • Others: Python, Ruby, and JavaScript require external libraries or have less efficient concurrency models.
  3. Performance:

    • Go: Compiled to machine code, offering fast execution and low memory overhead.
    • Others: Interpreted languages (Python, Ruby) are slower; Java requires JVM.
  4. Deployment:

    • Go: Produces single static binaries, making deployment straightforward.
    • Others: Java needs JVM, Python needs interpreter, C++ may have dependency issues.
  5. Ecosystem:

    • Go: Strong in cloud, DevOps, and networking (used in Docker, Kubernetes).
    • Others: Java excels in enterprise, Python in data science, C++ in systems programming.
  6. Memory Management:

    • Go: Automatic garbage collection with some manual control.
    • Others: C/C++ require manual management; Java/Python are fully automatic.
  7. Use Cases:

    • Go: Ideal for microservices, cloud infrastructure, CLI tools, and networking.
    • Others: Java for enterprise, Python for ML/AI, C++ for performance-critical systems.

Summary: Go stands out for its simplicity, efficient concurrency, fast deployment, and suitability for modern cloud and infrastructure projects.

References:

Conclusion: Introduction to Go Programming.

💬 If you enjoyed reading this blog post and found it informative, please take a moment to share your thoughts by leaving a review and liking it 😀 and follow me in dev.to , linkedin, github

Top comments (0)