Go – Type Conversion ”; Previous Next Type conversion 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. Its syntax is as follows − type_name(expression) Example Consider the following example where the cast operator causes the division of one integer variable by another to be performed as a floating number operation. Live Demo package main import “fmt” func main() { var sum int = 17 var count int = 5 var mean float32 mean = float32(sum)/float32(count) fmt.Printf(“Value of mean : %fn”,mean) } When the above code is compiled and executed, it produces the following result − Value of mean : 3.400000 Print Page Previous Next Advertisements ”;
Category: go
Go – Environment Setup
Go – Environment Setup ”; Previous Next Local Environment Setup If you are still willing to set up your environment for Go programming language, you need the following two software available on your computer − A text editor Go compiler Text Editor You will require a text editor to type your programs. Examples of text editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. The name and version of text editors can vary on different operating systems. For example, Notepad is used on Windows, and vim or vi is used on Windows as well as Linux or UNIX. The files you create with the text editor are called source files. They 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 a 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 and turned into machine language so that your CPU can actually execute the program as per the instructions given. The Go programming language compiler compiles the source code into its final executable program. 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 32-bit (386) and 64-bit (amd64) x86 processor architectures. The following section explains how to install Go binary distribution on various OS. Download Go Archive Download the latest version of Go installable archive file from Go Downloads. The following version is used in this tutorial: go1.4.windows-amd64.msi. It is copied it into C:>go folder. OS Archive name Windows go1.4.windows-amd64.msi Linux go1.4.linux-amd64.tar.gz Mac go1.4.darwin-amd64-osx10.8.pkg FreeBSD go1.4.freebsd-amd64.tar.gz Installation on UNIX/Linux/Mac OS X, and FreeBSD Extract the download archive into the folder /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. OS Output Linux export PATH = $PATH:/usr/local/go/bin Mac export PATH = $PATH:/usr/local/go/bin FreeBSD export 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:Gobin directory in Window”s PATH environment variable. Restart any open command prompts for the change to take effect. Verifying the Installation Create a go file named test.go in C:>Go_WorkSpace. File: test.go Live Demo package main import “fmt” func main() { fmt.Println(“Hello, World!”) } Now run test.go to see the result − C:Go_WorkSpace>go run test.go Output Hello, World! Print Page Previous Next Advertisements ”;
Go – Error Handling
Go – Error Handling ”; Previous Next Go programming provides a pretty simple error handling framework with inbuilt error interface type of the following declaration − type error interface { Error() string } Functions normally return error as last return value. Use errors.New to construct a basic error message as following − func Sqrt(value float64)(float64, error) { if(value < 0){ return 0, errors.New(“Math: negative number passed to Sqrt”) } return math.Sqrt(value), nil } Use return value and error message. result, err:= Sqrt(-1) if err != nil { fmt.Println(err) } Example Live Demo package main import “errors” import “fmt” import “math” func Sqrt(value float64)(float64, error) { if(value < 0){ return 0, errors.New(“Math: negative number passed to Sqrt”) } return math.Sqrt(value), nil } func main() { result, err:= Sqrt(-1) if err != nil { fmt.Println(err) } else { fmt.Println(result) } result, err = Sqrt(9) if err != nil { fmt.Println(err) } else { fmt.Println(result) } } When the above code is compiled and executed, it produces the following result − Math: negative number passed to Sqrt 3 Print Page Previous Next Advertisements ”;
Go – Constants
Go – Constants ”; Previous Next Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well. Constants are treated just like regular variables except that their values cannot be modified after their definition. Integer Literals An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal. An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order. Here are some examples of integer literals − 212 /* Legal */ 215u /* Legal */ 0xFeeL /* Legal */ 078 /* Illegal: 8 is not an octal digit */ 032UU /* Illegal: cannot repeat a suffix */ Following are other examples of various type of Integer literals − 85 /* decimal */ 0213 /* octal */ 0x4b /* hexadecimal */ 30 /* int */ 30u /* unsigned int */ 30l /* long */ 30ul /* unsigned long */ Floating-point Literals A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form. While representing using decimal form, you must include the decimal point, the exponent, or both and while representing using exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E. Here are some examples of floating-point literals − 3.14159 /* Legal */ 314159E-5L /* Legal */ 510E /* Illegal: incomplete exponent */ 210f /* Illegal: no decimal or exponent */ .e55 /* Illegal: missing integer or fraction */ Escape Sequence When certain characters are preceded by a backslash, they will have a special meaning in Go. These are known as Escape Sequence codes which are used to represent newline (n), tab (t), backspace, etc. Here, you have a list of some of such escape sequence codes − Escape sequence Meaning \ character ” ” character “ ” character ? ? character a Alert or bell b Backspace f Form feed n Newline r Carriage return t Horizontal tab v Vertical tab ooo Octal number of one to three digits xhh . . . Hexadecimal number of one or more digits The following example shows how to use t in a program − Live Demo package main import “fmt” func main() { fmt.Printf(“HellotWorld!”) } When the above code is compiled and executed, it produces the following result − Hello World! String Literals in Go String literals or constants are enclosed in double quotes “”. A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters. You can break a long line into multiple lines using string literals and separating them using whitespaces. Here are some examples of string literals. All the three forms are identical strings. “hello, dear” “hello, dear” “hello, ” “d” “ear” The const Keyword You can use const prefix to declare constants with a specific type as follows − const variable type = value; The following example shows how to use the const keyword − Live Demo package main import “fmt” func main() { const LENGTH int = 10 const WIDTH int = 5 var area int area = LENGTH * WIDTH fmt.Printf(“value of area : %d”, area) } When the above code is compiled and executed, it produces the following result − value of area : 50 Note that it is a good programming practice to define constants in CAPITALS. Print Page Previous Next Advertisements ”;
Go – Operators
Go – Operators ”; Previous Next 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 Miscellaneous Operators This tutorial explains 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 − Show Examples Operator Description Example + Adds two operands A + B gives 30 – Subtracts second operand from the first A – B gives -10 * Multiplies both operands A * B gives 200 / Divides the numerator by the denominator. B / A gives 2 % Modulus operator; gives the remainder after an integer division. B % A gives 0 ++ Increment operator. It increases the integer value by one. A++ gives 11 — Decrement operator. It decreases the integer value by one. A– gives 9 Relational Operators The following table lists all the relational operators supported by Go language. Assume variable A holds 10 and variable B holds 20, then − Show Examples Operator Description Example == It checks if the values of two operands are equal or not; if yes, the condition becomes true. (A == B) is not true. != It checks if the values of two operands are equal or not; if the values are not equal, then the condition becomes true. (A != B) is true. > It checks if the value of left operand is greater than the value of right operand; if yes, the condition becomes true. (A > B) is not true. < It checks if the value of left operand is less than the value of the right operand; if yes, the condition becomes true. (A < B) is true. >= It checks if the value of the left operand is greater than or equal to the value of the right operand; if yes, the condition becomes true. (A >= B) is not true. <= It checks if the value of left operand is less than or equal to the value of right operand; if yes, the condition becomes true. (A <= B) is true. Logical Operators The following table lists all the logical operators supported by Go language. Assume variable A holds 1 and variable B holds 0, then − Show Examples Operator Description Example && 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. The following table shows all the logical operators supported by Go language. Assume variable A holds true and variable B holds false, then − Operator Description Example && Called Logical AND operator. If both the operands are false, then the condition becomes false. (A && B) is false. || Called Logical OR Operator. If any of the two operands is true, then the 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 it false. !(A && B) is true. Bitwise Operators Bitwise operators work on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows − p q p & q p | q p ^ q 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 1 Assume A = 60; and B = 13. 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 − Show Examples Operator Description Example & 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 The following table lists all the assignment operators supported by Go language − Show Examples Operator Description Example = 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
Go – Recursion
Go – Recursion ”; Previous Next Recursion is the process of repeating items in a self-similar way. The same concept applies in programming languages as well. If a program allows to call a function inside the same function, then it is called a recursive function call. Take a look at the following example − func recursion() { recursion() /* function calls itself */ } func main() { recursion() } The Go programming language supports recursion. That is, it allows 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 on to become an infinite loop. Examples of Recursion in Go Recursive functions are very useful to solve many mathematical problems such as calculating factorial of a number, generating a Fibonacci series, etc. Example 1: Calculating Factorial Using Recursion in Go The following example calculates the factorial of a given number using a recursive function − Live Demo package main import “fmt” func factorial(i int)int { if(i <= 1) { return 1 } return i * factorial(i – 1) } func main() { var i int = 15 fmt.Printf(“Factorial of %d is %d”, i, factorial(i)) } When the above code is compiled and executed, it produces the following result − Factorial of 15 is 1307674368000 Example 2: Fibonacci Series Using Recursion in Go The following example shows how to generate a Fibonacci series of a given number using a recursive function − Live Demo package main import “fmt” func fibonaci(i int) (ret 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 “, 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 Print Page Previous Next Advertisements ”;
Go – Useful Resources
Go – Useful Resources ”; Previous Next The following resources contain additional information on Go. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Javascript Object oriented programming Course – Build Quiz App 61 Lectures 8 hours DigiFisk (Programming Is Fun) More Detail Industry 4.0 – Automation & Applications 35 Lectures 2.5 hours J Aatish Rao More Detail Java Courses in Tamil 188 Lectures 11.5 hours Programming Line More Detail Python for Beginners with Real world applications in Hindi 54 Lectures 8 hours Saurabh Dubey More Detail Data Science and Machine Learning with R from A-Z Course [Updated for 2021] 81 Lectures 28.5 hours Packt Publishing More Detail Internet of Things (IoT) Automation using Raspberry Pi 2 23 Lectures 39 mins Venkatesh Varadachari More Detail Print Page Previous Next Advertisements ”;
Go – Slice
Go – Slices ”; Previous Next Go Slice is an abstraction over Go Array. Go Array allows you to define variables that can hold several data items of the same kind but it does not provide any inbuilt method to increase its size dynamically or get a sub-array of its own. Slices overcome this limitation. It provides many utility functions required on Array and is widely used in Go programming. Defining a slice To define a slice, you can declare it as an array without specifying its size. Alternatively, you can use make function to create a slice. var numbers []int /* a slice of unspecified size */ /* numbers == []int{0,0,0,0,0}*/ numbers = make([]int,5,5) /* a slice of length 5 and capacity 5*/ len() and cap() functions A slice is an abstraction over array. It actually uses arrays as an underlying structure. The len() function returns the elements presents in the slice where cap() function returns the capacity of the slice (i.e., how many elements it can be accommodate). The following example explains the usage of slice − Live Demo package main import “fmt” func main() { var numbers = make([]int,3,5) printSlice(numbers) } func printSlice(x []int){ fmt.Printf(“len=%d cap=%d slice=%vn”,len(x),cap(x),x) } When the above code is compiled and executed, it produces the following result − len = 3 cap = 5 slice = [0 0 0] Nil slice If a slice is declared with no inputs, then by default, it is initialized as nil. Its length and capacity are zero. For example − Live Demo package main import “fmt” func main() { var numbers []int printSlice(numbers) if(numbers == nil){ fmt.Printf(“slice is nil”) } } func printSlice(x []int){ fmt.Printf(“len = %d cap = %d slice = %vn”, len(x), cap(x),x) } When the above code is compiled and executed, it produces the following result − len = 0 cap = 0 slice = [] slice is nil Subslicing Slice allows lower-bound and upper bound to be specified to get the subslice of it using[lower-bound:upper-bound]. For example − Live Demo package main import “fmt” func main() { /* create a slice */ numbers := []int{0,1,2,3,4,5,6,7,8} printSlice(numbers) /* print the original slice */ fmt.Println(“numbers ==”, numbers) /* print the sub slice starting from index 1(included) to index 4(excluded)*/ fmt.Println(“numbers[1:4] ==”, numbers[1:4]) /* missing lower bound implies 0*/ fmt.Println(“numbers[:3] ==”, numbers[:3]) /* missing upper bound implies len(s)*/ fmt.Println(“numbers[4:] ==”, numbers[4:]) numbers1 := make([]int,0,5) printSlice(numbers1) /* print the sub slice starting from index 0(included) to index 2(excluded) */ number2 := numbers[:2] printSlice(number2) /* print the sub slice starting from index 2(included) to index 5(excluded) */ number3 := numbers[2:5] printSlice(number3) } func printSlice(x []int){ fmt.Printf(“len = %d cap = %d slice = %vn”, len(x), cap(x),x) } When the above code is compiled and executed, it produces the following result − len = 9 cap = 9 slice = [0 1 2 3 4 5 6 7 8] numbers == [0 1 2 3 4 5 6 7 8] numbers[1:4] == [1 2 3] numbers[:3] == [0 1 2] numbers[4:] == [4 5 6 7 8] len = 0 cap = 5 slice = [] len = 2 cap = 9 slice = [0 1] len = 3 cap = 7 slice = [2 3 4] append() and copy() Functions One can increase the capacity of a slice using the append() function. Using copy()function, the contents of a source slice are copied to a destination slice. For example − Live Demo package main import “fmt” func main() { var numbers []int printSlice(numbers) /* append allows nil slice */ numbers = append(numbers, 0) printSlice(numbers) /* add one element to slice*/ numbers = append(numbers, 1) printSlice(numbers) /* add more than one element at a time*/ numbers = append(numbers, 2,3,4) printSlice(numbers) /* create a slice numbers1 with double the capacity of earlier slice*/ numbers1 := make([]int, len(numbers), (cap(numbers))*2) /* copy content of numbers to numbers1 */ copy(numbers1,numbers) printSlice(numbers1) } func printSlice(x []int){ fmt.Printf(“len=%d cap=%d slice=%vn”,len(x),cap(x),x) } When the above code is compiled and executed, it produces the following result − len = 0 cap = 0 slice = [] len = 1 cap = 2 slice = [0] len = 2 cap = 2 slice = [0 1] len = 5 cap = 8 slice = [0 1 2 3 4] len = 5 cap = 16 slice = [0 1 2 3 4] Print Page Previous Next Advertisements ”;
Go – Quick Guide
Go – Quick Guide ”; Previous Next Go – Overview Go is a general-purpose language designed with systems programming in mind. It was initially developed at Google in the 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. The Go programming language was announced in November 2009 and is used in some of the Google”s production systems. Features of Go Programming The most important features of Go programming are listed below − Support for environment adopting patterns similar to dynamic languages. For example, type inference (x := 0 is valid declaration of a variable x of type int) Compilation time is fast. Inbuilt concurrency support: lightweight processes (via go routines), channels, select statement. Go programs are simple, concise, and safe. Support for Interfaces and Type embedding. Production of statically linked native binaries without external dependencies. Features Excluded Intentionally To keep the language simple and concise, the following features commonly available in other similar languages are omitted in Go − Support for type inheritance Support for method or operator overloading Support for circular dependencies among packages Support for pointer arithmetic Support for assertions Support for generic programming Go Programs A Go program can vary in length from 3 lines to millions of lines and it should be written into one or more text files with the extension “.go”. For example, hello.go. You can use “vi”, “vim” or any other text editor to write your Go program into a file. Go – Environment Setup Local Environment Setup If you are still willing to set up your environment for Go programming language, you need the following two software available on your computer − A text editor Go compiler Text Editor You will require a text editor to type your programs. Examples of text editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. The name and version of text editors can vary on different operating systems. For example, Notepad is used on Windows, and vim or vi is used on Windows as well as Linux or UNIX. The files you create with the text editor are called source files. They 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 a 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 and turned into machine language so that your CPU can actually execute the program as per the instructions given. The Go programming language compiler compiles the source code into its final executable program. 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 32-bit (386) and 64-bit (amd64) x86 processor architectures. The following section explains how to install Go binary distribution on various OS. Download Go Archive Download the latest version of Go installable archive file from Go Downloads. The following version is used in this tutorial: go1.4.windows-amd64.msi. It is copied it into C:>go folder. OS Archive name Windows go1.4.windows-amd64.msi Linux go1.4.linux-amd64.tar.gz Mac go1.4.darwin-amd64-osx10.8.pkg FreeBSD go1.4.freebsd-amd64.tar.gz Installation on UNIX/Linux/Mac OS X, and FreeBSD Extract the download archive into the folder /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. OS Output Linux export PATH = $PATH:/usr/local/go/bin Mac export PATH = $PATH:/usr/local/go/bin FreeBSD export 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:Gobin directory in Window”s PATH environment variable. Restart any open command prompts for the change to take effect. Verifying the Installation Create a go file named test.go in C:>Go_WorkSpace. File: test.go Live Demo package main import “fmt” func main() { fmt.Println(“Hello, World!”) } Now run test.go to see the result − C:Go_WorkSpace>go run test.go Output Hello, World! Go – Program Structure Before we study the basic building blocks of Go programming language, let us first discuss the bare minimum structure of Go programs so that we can take it as a reference in subsequent chapters. Hello World Example A Go program basically consists of the following parts − Package Declaration Import Packages Functions Variables Statements and Expressions Comments Let us look at a simple code that would print the words “Hello World” − Live Demo package main import “fmt” func main() { /* This is my first sample program. */ fmt.Println(“Hello, World!”) } Let us take a look at the various parts of the above program − The first line of the program package main defines the package name in which this program should lie. It is a mandatory statement, as Go programs run in packages. The main package is the starting point to run the program. Each package has a path and name associated with it. The next line import “fmt” is a preprocessor command which tells the Go compiler to include the files lying in the package fmt. The next line func main() is the main function where the program execution begins. The next line /*…*/ is ignored by the compiler and it is there to add comments in the program. Comments are also represented using // similar to Java or C++ comments. The next line fmt.Println(…) is another function available in Go which causes the message “Hello, World!” to be displayed on the screen. Here fmt package has exported Println method which is used to display the message on the screen.
Go – Discussion
Discuss Go ”; Previous Next Go language is a programming language initially developed at Google in the year 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. It is a statically-typed language having syntax similar to that of C. It provides garbage collection, type safety, dynamic-typing capability, many advanced built-in types such as variable length arrays and key-value maps. It also provides a rich standard library. The Go programming language was launched in November 2009 and is used in some of the Google”s production systems. Print Page Previous Next Advertisements ”;