golang – Linux Hint https://linuxhint.com Exploring and Master Linux Ecosystem Mon, 01 Mar 2021 00:18:05 +0000 en-US hourly 1 https://wordpress.org/?v=5.6.2 How to Create a Simple Application in Go Language https://linuxhint.com/create_simple_application_go_language/ Tue, 22 Dec 2020 13:20:52 +0000 https://linuxhint.com/?p=82507

This article will cover a tutorial on creating a simple “Hello World” application in Go programming language. All code samples and commands in this article are tested with the Go language version 1.14.7 on Ubuntu 20.10.

About Go Language

Go is a relatively new programming language being developed at Google. It is similar to C and C++ in many ways, with some very useful additions that makes writing code and rapid prototyping much simpler and safer. It is a compiled programming language and features statically typed syntax (like C). It also features automatic garbage collection and code written in Go is much more readable than other similar compiled programming languages. In simplest terms, you can think of it as a programming language created by picking up the best features from both C and Python. Go is faster than Python and its speed is comparable to C, even faster in many cases. Go does not provide object oriented programming structure and classes you may have seen in other programming languages. Though there are ways to make methods behave like classes in Go language.

Installing Go Language in Linux

You can install Go programming language in Ubuntu by running the command mentioned below:

$ sudo apt install golang

Go language has been packaged and included in repositories of all major Linux distributions. You can install Go language packages from the default package manager. You can also directly download binaries from the official Go language webpage. Once you have downloaded the tar archive, run the commands specified below in succession to install Go language. Make sure to replace the name in the first command with the name of the archive you have downloaded from the official Go website.

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

$ echo "export PATH=$PATH:/usr/local/go/bin" >> "$HOME/.bashrc"

$ source$HOME/.bashrc”

To verify that Go has been successfully installed on your system and its compiler working properly, use the following command:

$ go version

You should see some output like this:

go version go1.14.7 linux/amd64

Full Code

Full code for a “Hello World” application in Go language is given below.

package main


import "fmt"


func main() {

    fmt.Println("Hello World !!")

}

The same “Hello World” application can be re-written in Go language emulating object oriented patterns:

package main


import "fmt"


type HandleString struct {

    name string

}


func (newString HandleString) print_string(){

    fmt.Println(newString.name)

}


func main() {

        s := HandleString{"Hello World !!"}

        s.print_string()

}

Assuming that any of the code samples above is saved into a file named “helloworld.go”, you can run the command below to execute the code:

$ go run helloworld.go

After executing the above code samples, you should get output like this:

Hello World !!

Step-by-step Explanation

The first statement “package main” is required to create an executable command or binary in Go language. Go source files under the same directory are put together into packages. All variables and functions in these source files can be shared between the specified packages.

Next, “fmt” package is imported so that you can use functions like “Println” in the main code. “Fmt” is a part of the standard library packages in Go language and it provides numerous useful helper functions. It is not mandatory but it is used in almost all programs written in Go language.

Lastly the “main” function prints “Hello World !!” string. The “main” function is automatically called whenever you execute a Go language program.

In the object oriented example, struct is used to define a new “HandleString” type. A struct is a group of data fields and variables. Functions can be attached to structs to handle these data groups. Thus structs provide a neat way to define classes in Go language. A new field “name” of type “string” is declared in the struct.

Next, the function “print_string” is added to the “HandleString” struct. This function has a “newString” argument that acts as “receiver”. This receiver can be used to access fields of a struct instance. For instance, “newString.name” is used to access the name field from “HandleString” struct.

Finally, a new instance of the “HandleString” struct is created and the function “print_string” is called on it to print the “Hello World !!” string.

Both code samples listed above produce the same output.

Compiling a Go Application

In order to compile “Hello World” Go program, you can use “build” command to generate an executable binary:

$ go build helloworld.go

You should now have a “helloworld” executable binary located in the same directory where your main program file is saved.

You can run the executable binary by using the command specified below:

$ ./helloworld

It will produce the same output as the “go run” command.

Conclusion

This tutorial touches only a few basics to create a “Hello World” program in Go language. It should get you started. To create more advanced programs, refer to official documentation.

]]>
Install Jetbrains GoLand Go IDE on Ubuntu https://linuxhint.com/install_jetbrains_goland_ubuntu/ Thu, 10 Jan 2019 06:43:10 +0000 https://linuxhint.com/?p=35285 GoLand is an amazing Go IDE by JetBrains. If you love other JetBrains IDEs then, you will love GoLand as well. GoLand will improve your Go development workflow with it’s amazing features such as intelligent auto completion, syntax highlighting, code snippets etc. In this article, I will show you how to install GoLand Go IDE on Ubuntu. So, let’s get started.

Installing Go Programming Language on Ubuntu:

In order to run Go programs with GoLand Go IDE, you must have Go programming language installed on your machine.

I’ve written a dedicated article on installing Go programming language on Ubuntu. If you don’t have Go programming language installed on your Ubuntu machine already, you may check it out at https://linuxhint.com/install-golang-ubuntu/

Downloading GoLand:

GoLand is not available in the official package repository of Ubuntu. But, you can easily download GoLand from the official package repository of JetBrains and install it on Ubuntu.

First, visit the official website of JetBrains at https://www.jetbrains.com. Then, go to Tools > GoLand as marked in the screenshot below.

Now, click on Download.

Make sure Linux is selected. Then, click on DOWNLOAD.’

Your browser should prompt you to download GoLand archive. Select Save File and click on OK.

Your download should start. It may take a while to complete.

Installing and Configuring GoLand:

Once the download is complete, you can install GoLand from the command line interface.

First, navigate to the directory where you downloaded GoLand archive with the following command:

$ cd ~/Downloads

As you can see, the file I just downloaded is here.

Now, run the following command to install GoLand in /opt directory:

$ sudo tar xzf goland-2018.3.2.tar.gz -C /opt

NOTE: If you want to install GoLand somewhere other than /opt directory, just replace /opt with the directory path where you want to install GoLand.

Now, type in your login password and press <Enter>. GoLand should be installed.

As you can see, a new directory is created inside the /opt directory. Note the directory name. It may be different by the time you read this article. Make sure to replace it with yours from now on.

You have to run GoLand from the command line for the first time. Run GoLand as follows:

$ /opt/GoLand-2018.3.2/bin/goland.sh

As you’re running GoLand for the first time, you may not have any settings to import. So, select Do not import settings and click on OK.

Now, you have to accept the GoLand User Agreement. To do that, select I confirm that I have read and accept the terms of this User Agreement and click on Continue.

You may not may not want to share usage data with JetBrains. Click on any of the buttons depending on whether you want to share GoLand usage data with JetBrains or not.

Now, you have to activate GoLand. To do that, you have to buy a license for GoLand from JetBrains. Once you have the license, you can type in the credentials here and activate GoLand.

If you want to try out GoLand before you buy it, then select Evaluate for free and click on Evaluate. You can try out GoLand for 30 days as of the time of this writing.

GoLand is being loaded.

This is the dashboard of GoLand. From here you can create new projects and manage your existing projects.

Now, you should create a Desktop shortcut of GoLand. This way, you can launch GoLand from the Application Menu of Ubuntu. To do that, click on Configure.

Then, select Create Desktop Entry.

Now, check Create the entry for all users (requires superuser privileges) checkbox and click on OK.

Now, type in the password of your login user and click on Authenticate.

GoLand desktop shortcut should be created as you can see in the screenshot below. Now, you can easily run GoLand from the Application Menu of Ubuntu.

Creating a Go Project with GoLand:

In this section, I will show you how to create a new Go project with GoLand and run a simple Go program.

First, start GoLand and click on New Project.

Now, select Go from the list and make sure the project Location (where all the project files will be saved) and GOROOT is selected correctly. Then, click on Create.

A new Go project will be created.

Now, create a new file hello.go and type in the following lines of codes.

Now, press <Alt> + <Shift> + <F10> or go to Run > Run… and then select hello.go from the list as shown in the screenshot below.

The Go source file should run. As you can see, the correct output is displayed.

So, that’s how you install GoLand Go IDE on Ubuntu. Thanks for reading this article.

]]>
Book Review: The Go Programming Language https://linuxhint.com/go_programming_language_donovan_kernighan/ Mon, 10 Dec 2018 12:20:36 +0000 https://linuxhint.com/?p=33478 The Go Programming Language, by Alan A. A. Donovan and Brian Kernighan, is reviewed in this post. Brian Kernighan is well known as the coauthor of The C Programming Language, and that book itself has severed as a standard text for generations of engineers. Go has often been referred to as the 21st Century C and The Go Programming Language may very well be the standard reference text for it.

The Beginning

The book starts out strong with a Tutorial chapter giving you a simple “Hello, World” program and also showing off some of the advantages of using Go. The minimalism is bound to appeal to programmers who have had it with bloated libraries. You can’t declare a variable and not use it in the rest of your Go program. You can’t import a library and not use it in your code. It will simply not compile. You don’t have to argue about the format of your code. For example, the age old battle between:

func main() {
}
//And
func main()
{
}

Is settled by the compiler which accepts only the former and not the latter. Other nuances are settled by tools like gofmt which takes your Go source file and formats it in a standardized manner. So all Go programs follow the same convention, which in turn improves the readability of the code.

The first chapter emphasizes these selling points and does a really good job of giving the readers a taste of what Go is really about: A general purpose language designed for generating static binaries with as little bloat as possible.

Brevity

Experienced programmers are tired of learning about the same concepts like for loops, if-else statements, etc over and over again for different languages. The first chapter sneaks in all this tedious information by encouraging the users to write simple Unix-y programs (as was the case with The C Programming language).

One drawback of this rapid-introduction is the fact that new readers will get completely baffled by syntax. Programs rapidly start using the dot operators and various object oriented programming concepts after two or three examples down the very first chapter. This is important for maintaining speed and brevity of the overall reading experience and is a very conscious choice on the part of the writers.

The book also assumes that readers are familiar with at least one programming language, before they picked up this book. This could be Python, JavaScript, Java, C or any other general purpose language.

Companion Website

The book comes with a companion website. You can directly import the programs given in the book from this website and run it without having to type (or copy paste from your Kindle App). You can even check out the first chapter (which, by the way, is my favorite one) for free on this website and decide if this book is for you or not.

The authors have paid attention to the pains of a programmer trying to learn a new language. Distractions are kept to a minimum with each program’s web link mentioned on top of it. So you can fetch the code, run it, tweak it and build upon it, if you like.

A comprehensive list of errata is also maintained on this website, and you can refer it if you think something’s amiss.

Serious Business

If you are expecting a simple guide for causal scripting, this is not the book for you. The reason is that a lot of ground is covered first and then the details are filled along as we progress towards later chapters.

This book is for people who want to understand the constructs, the nitty-gritty details of how Go works. You will be creating GIFs, writing web servers and  plotting Mandelbrot Sets and much much more, but none of it would make any sense unless you have paid attention to the finer points made  preceding chapters (with the Chapter 1 being somewhat of an exception, as it is meant as an overview of the language).

The majority of the rest of the book focuses on various syntax related details about Go including things control loops, variables, functions, methods, Go routines and much much more. All of this is illustrated by making the reader go through useful programs and not made-up idealistic scenarios.

Even if you wish to skip most chapters from the middle of the book, I would strongly suggest digging through chapter 5 for an understanding of Panic, Error handling and anonymous functions. However, I would strongly suggest going through all the chapters sequentially before we come to the crown-jewel of Go — Concurrency.

Emphasis on Concurrency

Go language is designed, from ground up with concurrency in mind. Most modern processors are multicore and multithreaded but programmers despise the complications they face when writing programs to run on such architecture. With cloud computing heading towards distributed systems, concurrent code will soon be the only well-performing code out there.

The chapter on concurrency is written to beat the fear of concurrent design out of our minds. It is complicated, yes, but not hopeless. The book does a great job of conveying how Go can help you develop the correct mindset from this.

Conclusion

The experience of Kernighan from early UNIX days is still very very viable in the modern age of cloud desktops, GPUs, IOT, cloud and whatever will follow next. He and Donovan have done a great job of imparting this wisdom of application design and UNIX philosophy using a simple, modern language with performance in mind and I have zero hesitation in recommending this book to anyone from a high school student to an senior software engineer with decades of experience.

]]> Golang Logrus Package https://linuxhint.com/golang-logrus-package/ Sat, 17 Feb 2018 13:21:42 +0000 https://linuxhint-com.zk153f8d-liquidwebsites.com/?p=22567

In this lesson on Logrus package in Golang, we will study various examples on how effective Logging can be done in Go and see how  important logs are in Go programming language. We will get started now.

Starting with Go

Here is the directory structure which I made for my Hello World program:

Here is the program we created:

package main

import "fmt"

func main() {
    fmt.Printf("Hello, world.\n")
}

We can run the above program with following command:

go run hello.go

Once we run this command, here is the output you will see:

Now that looks good. Let’s move to our main agenda.

Logrus Package in Golang

To start using Logrus package in the Go program, we must get it. Run the following command:

go get -t github.com/Sirupsen/logrus

When we start using this package in IntelliJ, we see this error which we can resolve in one click:

Once you get the package, we can start to use it. Let’s start with a simple program.

Basic Logging with Logrus

We will start with very basic INFO level logging example. Logging can be done with String messages and meta-data in form of key-value pairs which appear like the same.

package main

import (
  log "github.com/Sirupsen/logrus"
)

func main() {
    log.WithFields(log.Fields{
      "website": "linuxhint.com",
      "awesome": 100,
      "help":   200,
      }).Info("Golang pro")
}

When we run this program, we can see the following output:

Now that is both useful and colorful!

Various Logging Levels

Now, we will try another example which will show the use of various Logging levels available in Logrus and in general. They are:

  • Info
  • Warning
  • Fatal
  • Debug
  • Panic

Let’s try to build a program and see how these log levels differ when they appear in our program:

package main

import (
  log "github.com/Sirupsen/logrus"
)

func main() {
    log.WithFields(log.Fields{
      "website": "linuxhint.com",
      "awesome": 100,
      }).Info("Golang pro INFO message")

    log.WithFields(log.Fields{
      "website": "linuxhint.com",
      "awesome": 100,
      }).Warn("Golang pro WARN message")

    log.WithFields(log.Fields{
      "website": "linuxhint.com",
      "awesome": 100,
      }).Fatal("Golang pro FATAL message")

    log.WithFields(log.Fields{
      "website": "linuxhint.com",
      "awesome": 100,
      }).Panic("Golang pro PANIC message")

    log.WithFields(log.Fields{
      "website": "linuxhint.com",
      "awesome": 100,
      }).Debug("Golang pro DEBUG message")
}

When we run this program, we will see the following output:

Noticed something? The log statements after the Fatal statement doesn’t even appear in our output. This is because as soon as a Fatal error is received, program execution stops in Golang.

Let’s modify the order of these statements and check if some changes in output are also observed:

This time, even Panic Log level reacted in the same manner but output was very different and detailed.

With Panic log level, you make sure that enough information about the host machine also printed in the output in the console so that the work is debuggable.

Simpler way to make Logs

In above calls, Logs were pretty detailed and with metadata as well. There is an easier way to log your messages. Let’s try this now:

package main

import (
  log "github.com/Sirupsen/logrus"
)

func main() {
    log.Debug("Debugging data here.")
    log.Info("Messages for common info")
    log.Warn("You should look at this warning!")
    log.Error("Something failed but program will continue.")
    // Calls os.Exit(1) after logging
    log.Fatal("I am leaving.")
    // Calls panic() after logging
    log.Panic("I won't be printed :(")
}

Here is the output for the program:

The behavior for logging was the same but this time, they were easy to make in just one line.

Conclusion

In this post, we studied simple but useful examples on how we can log important messages with different severity and verbosity in our applications using the Logrus package with Golang.

]]>
Golang Crypto Package https://linuxhint.com/golang-crypto-package/ Sun, 11 Feb 2018 04:18:40 +0000 https://linuxhint-com.zk153f8d-liquidwebsites.com/?p=22338 In this lesson on Crypto package in Golang, we will study various examples on managing and creating Ciphers in Go and see how Crypto package helps us in regards to Cipher Handling in Go programming language. We will get started now.

Starting with Go

Just to make sure we are on the same page, here is the directory structure which I made for my Hello World program:

Here is the program we created:

package main

import "fmt"

func main() {
    fmt.Printf("Hello, world.\n")
}

We can run the above program with following command:

go run hello.go

Once we run this command, here is the output you will see:

Now that looks good. Let’s move to our main agenda.

Crypto Package in Golang

Using Crypto in Golang isn’t very easy to understand. This is because of the constructs it provides and the algorithm it follows to achieve encryption and decryption.

In this lesson, we will study these points:

  • SHA256 encryption
  • How to use bcrypt to encrypt Strings like passwords in your web applications
  • Using AES encryption and decryption

Let’s start by Hashing and comparing passwords.

SHA256 Encryption

We will start with somewhat simple. We will try a very simple example on how to perform an SHA256 encryption using Golang. Let’s look at the example:

package main

import (
  "fmt"
  "errors"
  "crypto/sha256"
  "encoding/base64"
)

func main() {
    someText := "shubham"
    hash, err := hashTextTo32Bytes(someText)
    fmt.Printf("%s\n %s", hash, err)
}

func hashTextTo32Bytes(hashThis string) (hashed string, err error) {

    if len(hashThis) == 0 {
        return "", errors.New("No input supplied")
    }

    hasher := sha256.New()
    hasher.Write([]byte(hashThis))

    stringToSHA256 := base64.URLEncoding.EncodeToString(hasher.Sum(nil))

    // Cut the length down to 32 bytes and return.
    return stringToSHA256[:32], nil
}

We started by creating a hasher initially. Following this, we used it to write the hash in a byte array. Finally, we encode the String and return the 32 bits of hash.

When we run this example, we will get the following output:

Hashing and Matching Password

Now, we will finally use bcrypt to produce Hashed passwords. We will keep the functions direct and simple.

We will also include a function which matches the hashed password to a given String. This way, we can also confirm if the password provided by the user is correct one.  Before running this code will need to install the golang package for bcrypt with the following command:

# go get "golang.org/x/crypto/bcrypt"

Then you can execute this code:

package main

import "fmt"
import "golang.org/x/crypto/bcrypt"

func HashPassword(password string) (string, error) {
    bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
    return string(bytes), err
}

func CheckPasswordHash(password, hash string) bool {
    err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
    return err == nil
}

func main() {
    myPwd := "shubham"
    providedHash, _ := HashPassword(myPwd)
    fmt.Println("Password :", myPwd)
    fmt.Println("Hash :", providedHash)

    isMatch := CheckPasswordHash(myPwd, providedHash)
    fmt.Println("Matched ?:", isMatch)
}

When we run this example, we will get the following output:

Conclusion

In this post, we studied simple but useful examples on how we can use crypto package to do actions very important and useful in our applications.

]]>
Golang Scanner Package https://linuxhint.com/golang-scanner-package/ Sat, 10 Feb 2018 05:00:37 +0000 https://linuxhint-com.zk153f8d-liquidwebsites.com/?p=22276

In this lesson on Scanner package in Golang, we will study various examples on how to use Scanners in multiple ways in Go programming language. We will get started now.

Starting with Go

Just to make sure we have the environment setup consistently, here is the directory structure which I made for my Hello World program:

Here is the program we created:

package main

import "fmt"

func main() {
    fmt.Printf("Hello, world.\n")
}

We can run the above program with the following command:

go run hello.go

Once we run this command, here is the output you will see:

Now that looks good. Let’s move to our main agenda.

Scanner and Bufio Package in Golang

In this post, we will go through the bufio and scanner packages.

We will start with a very simple example to split Strings into multiple words. Let’s at the following example:

package main

import (
    "bufio"
    "fmt"
    "strings"
)

func main() {
    inputStr := "golang shubham linux"
    scanner := bufio.NewScanner(strings.NewReader(inputStr))
    scanner.Split(bufio.ScanWords)
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }
}

The output of this program will be:

golang
shubham
linux

Here, Scanner used buffered input output by reading provided input as a Stream.

Reading a file

Now, let’s try reading a file in Go, using bufio to read a file line by line. To do this, first we create a sample file in the same directory as our Go program. Here is our file:

Next, we write our program to read this file line by line:

package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
)

func main() {
    fileToRead, error := os.Open("./hello.txt")
    if error != nil {
        log.Fatal(error)
    }
    defer fileToRead.Close()

    scanner := bufio.NewScanner(fileToRead)
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }

    if error := scanner.Err(); error != nil {
        log.Fatal(error)
    }
}

Once we run this program, here is the output we will get

Taking User Input with bufio

This is the most useful operation actually to be performed when a user is starting with the Golang language.

We can take a user input like:

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter text: ")
    text, _ := reader.ReadString('\n')
    fmt.Println(text)
}

Let’s run this program now:

Just to note, there is another way to take input if you are Ok NOT accepting a whitespace in it:

package main

import "fmt"

var input string

func main() {
    fmt.Print("Enter Your Name=")
    fmt.Scanf("%s",&input)
    fmt.Println("Hello "+input)
}

Let’s run this program now:

Conclusion

To study, Scanner and Bufio package in Go is very useful and it is never possible to get enough. Read more examples for the package and try as much as possible on your own.

]]>
Golang Strings https://linuxhint.com/golang-strings/ Mon, 05 Feb 2018 08:04:41 +0000 https://linuxhint-com.zk153f8d-liquidwebsites.com/?p=22134

Strings package in Golang

Overview

In this lesson on String package in Golang, we will study various examples on managing Strings and see how Strings package helps us in regards to Strings Handling in Go programming language. We will get started now.

Starting with Go

Just to make sure we are on the right track of running Go programs, here is the directory structure which I made for my Hello World program:

package main

import "fmt"

func main() {
    fmt.Printf("Hello, world.\n")
}

We can run the above program with following command:

go run hello.go

Once we run this command, here is the output you will see:

Now that looks good. Let’s move to our main agenda.

String Handling

Let’s start our journey of handling Strings in Go. We will be exploring the strings package in Go to study various examples. Let’s get started.

 Comparing Strings

Comparing Strings is the most common operation done in the any programming language actually. Let’s look at some code snippet now:

package main

import (
"fmt"
"strings"
)

func main() {
    var str1 string = "Shubham"
    var str2 string = "Linux"
    var str3 string = "linux"
    var str4 string = "Linux"

    fmt.Println(strings.Compare(str1, str2))
    fmt.Println(strings.Compare(str2, str3))
    fmt.Println(strings.Compare(str4, str2))
}

Again, we can run the above program with following command:

go run StringCompare.go

Once we run this command, here is the output you will see:

So, here is the output explained:

  • 1 appears as the first String comes after the second String alphabetically
  • -1 comes as ‘Linux’ comes before ‘linux’ when ASCII values are compared
  • comes when String objects are found to be exactly the same

Containing Strings

Now, we will check if a String is a substring of another String. Let’s look at some code snippet now:

package main

import (
"fmt"
"strings"
)

func main() {
    var mainString string = "Linux"
    fmt.Println(strings.Contains(mainString, "ux"))
    fmt.Println(strings.Contains(mainString, "UX"))
    fmt.Println(strings.Contains(mainString, "Lin"))
}

Again, we can run the above program with following command:

go run StringContains.go

Once we run this command, here is the output you will see:

In this case, output is self-explanatory.

Index of Substring

We can also find the index where the given substring is found first. Let’s look at some code snippet now:

package main

import (
"fmt"
"strings"
)

func main() {
    var mainString string = "Shubham"
    var subs string = "bha"

    fmt.Println(strings.Index(mainString, subs))
}

We can run the above program with following command:

go run StringIndex.go

Once we run this command, here is the output you will see:

Replacing part of Strings

We can replace part of Strings in Go as well. Let’s look at some code snippet now:

package main

import "fmt"
import s "strings"

func main() {
    var mainString string = "Linux"
    var toReplace string = "Li"
    var newPart string = "Te"

    fmt.Println(s.Replace(mainString, toReplace, newPart, -1))
}

In above program, we also saw a slightly different way of importing a package and assigning it an alias name. We can run the above program with following command:

go run StringReplace.go

Once we run this command, here is the output you will see:

Splitting Strings

We can even break Strings in Go by providing a common pattern which might be occurring. Here is an example:

package main

import "fmt"
import s "strings"

func main() {
    var mainString string = "L-i-n-u-x"
    var splitter string = "-"
    fmt.Println(s.Split(mainString, splitter))
}

We can run the above program with following command:

go run StringSplit.go

Once we run this command, here is the output you will see:

Conclusion

To study, Strings package in Go is very deep and it is never possible to get enough. Read more examples for the package and try as much as possible on your own.

]]>
Install GoLang on Ubuntu and Write Your First Program https://linuxhint.com/install-golang-ubuntu/ Thu, 11 Jan 2018 15:48:12 +0000 https://linuxhint-com.zk153f8d-liquidwebsites.com/?p=21444

Install GoLang on Ubuntu and Write Your First Program in Go

GoLang is a very powerful programming language developed by Google. It is a compiled programming language. It means, Go source codes are converted to machine code or commonly known as executable file. Then you can run these executable files on other computers. Unlike Java that converts source code to byte code, then runs these byte codes using JVM (Java Virtual Machine), Go does not use any VM (Virtual Machines). It is not an interpreted language either like Python or PHP. It is very fast and built with concurrency in mind. GoLang is widely used for Web Development because it has many libraries available for such stuff.

In this article, I will show you how to install the GoLang on different versions of Ubuntu operating system and how to write, run and build your first program with Go. Let’s get started.

Installing GoLang:

GoLang is available in the official package repository of Ubuntu.  First update the package repository cache of your Ubuntu operating system with the following command:

$ sudo apt-get update

Your package repository cache should be updated.

Now you can install GoLang from the official repository of Ubuntu.

Ubuntu 16.04 LTS:

On Ubuntu 16.04LTS, you can install GoLang 1.6 from the official repository of Ubuntu. This is the recommended version of GoLang on Ubuntu 16.04 LTS.

To install GoLang 1.6 from the official repository of Ubuntu 16.04 LTS, run the following command:

$ sudo apt-get install golang

If you want to install GoLang 1.9 on Ubuntu 16.04 LTS, enable the ‘xenial-backports’ ‘universe’ repository and run the following command:

$ sudo apt-get install golang-1.9

Ubuntu 17.10:

On Ubuntu 17.10, you can install GoLang 1.7, GoLang 1.8 and GoLang 1.9.
To install GoLang 1.8 on Ubuntu 17.10, you can run the following command:

$ sudo apt-get install golang

Or

$ sudo apt-get install golang-1.8

To install GoLang 1.7 on Ubuntu 17.10, run the following command:

$ sudo apt-get install golang-1.7

To install GoLang 1.9 on Ubuntu 17.10, run the following command:

$ sudo apt-get install golang-1.9

I am using Ubuntu 17.10 for the demonstration in this article. I will install GoLang 1.8.

$ sudo apt-get install golang

Once you run the command to install the version of GoLang you want, you should see the following prompt. Just press ‘y’ and then press <Enter> to continue.

GoLang should be installed.

Testing GoLang:

Now run the following command to verify that Go commands are accessible:

$ go version

You should see similar output as shown in the screenshot below. It means Go is working correctly.

Writing your First “Hello World” Program on GoLang:

The very first program that most people write while learning a language is the “Hello World” program. I would say, “It’s the gateway to the heart of the programming language”. It is very simple. All a “Hello World” program does is; it prints “Hello World” to the console or terminal.

Now I am going to write a simple “Hello World” program in Go.

This is the code that I am going to run.

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

It is saved in ‘~/work/helloworld.go’ file. Remember to save GoLang source files with .go extension.

GoLang can be used like an interpreted language like Python. It means that you can run a GoLang source file directly without manually compiling it first.

To run a go program, run the following command:

$ go run GO_SOURCE_FILE

In my case GO_SOURCE_FILE is ‘helloworld.go’.

$ go run helloworld.go

You should be able to see “Hello World!” output on the console as shown in the screenshot below.

The good thing about GoLang is that, you can also build an executable file out of GoLang source code. So it can be executed just as C or C++ programs.

Run the following command to compile Go source code:

$ go build GO_SOURCE_FILE

In my case, GO_SOURCE_FILE is ‘helloworld.go’.

$ go build helloworld.go

It should generate an executable file ‘helloworld’ as shown in the screenshot below.

Now you can run the executable as follows:

$ ./helloworld

You should see “Hello World!” on the terminal just like before.

So this is how you install GoLang on Ubuntu and write your first program in GoLang. Thanks for reading this article.

]]>
Install Golang 1.7.x Programming Language on Linux https://linuxhint.com/golang-1-7-programming-language-linux/ https://linuxhint.com/golang-1-7-programming-language-linux/#respond Thu, 19 Jan 2017 19:33:56 +0000 http://sysads.co.uk/?p=16068 Golang is an open source programming language that makes it easy to build simple, reliable, and efficient software. The latest Golang release, v1.7, arrives six months after 1.6. Most of its changes are in the implementation of the toolchain, runtime, and libraries.

The release adds a port to IBM LinuxOne; updates the x86-64 compiler back end to generate more efficient code; includes the context package, promoted from the x/net subrepository and now used in the standard library; and adds support in the testing package for creating hierarchies of tests and benchmarks. The release also finalizes the vendoring support started in Go 1.5, making it a standard feature.

golang programming language

Go 1.7 Key Changelog

Ports

  • Go 1.7 adds support for macOS 10.12 Sierra. Binaries built with versions of Go before 1.7 will not work correctly on Sierra.
  • Go 1.7 adds an experimental port to Linux on z Systems (linux/s390x) and the beginning of a port to Plan 9 on ARM (plan9/arm).
  • The experimental ports to Linux on 64-bit MIPS (linux/mips64 and linux/mips64le) added in Go 1.6 now have full support for cgo and external linking.
  • The OpenBSD port now requires OpenBSD 5.6 or later, for access to the getentropy(2) system call.

Go Command

  • This release removes support for the GO15VENDOREXPERIMENT environment variable, as announced in the Go 1.6 release. Vendoring support is now a standard feature of the go command and toolchain.
  • This release adds experimental, minimal support for building programs using binary-only packages, packages distributed in binary form without the corresponding source code

Performance

  • There have been significant optimizations bringing more than 10% improvements to implementations

See changelog for full details

How to install latest Golang 1.7.x on Ubuntu 17.04, Ubuntu 16.10, Ubuntu 16.04, Ubuntu 15.04, Ubuntu 14.04

---------- Download latest package 32bit OS ----------

wget https://storage.googleapis.com/golang/go1.7.4.linux-386.tar.gz

---------- Download latest package 64bit OS----------

wget https://storage.googleapis.com/golang/go1.7.4.linux-amd64.tar.gz

---------- Extract download package ----------

tar xvf go1.7*

---------- Move extracted folder to "/usr/local" ----------

sudo chown -R root:root ./go

sudo mv go /usr/local

---------- Edit profile using vim or any other text editor ----------

vim ~/.profile

---------- Add following bash variables to profile so Golang knows where the directory is located ----------

export GOPATH=$HOME/work
export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin

---------- Reload the updated profile ----------

source ~/.profile

---------- Check version installed ----------

go version
]]>
https://linuxhint.com/golang-1-7-programming-language-linux/feed/ 0