Go – Overview

Go – Overview ”; Previous Next 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. Print Page Previous Next Advertisements ”;

Go – Home

Go Tutorial PDF Version Quick Guide Resources Job Search Discussion 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. Audience This tutorial is designed for software programmers with a need to understand the Go programming language from scratch. This tutorial will give you enough understanding on Go programming language from where you can take yourself to higher levels of expertise. Prerequisites Before proceeding with this tutorial, you should have a basic understanding of computer programming terminologies. If you have a good command over C, then it would be quite easy for you to understand the concepts of Go programming and move fast on the learning track. Print Page Previous Next Advertisements ”;

Go – Variables

Go – Variables ”; Previous Next A variable is nothing but a name given to a storage area that the programs can manipulate. Each variable in Go has a specific type, which determines the size and layout of the variable”s memory, the range of values that can be stored within that memory, and the set of operations that can be applied to the variable. The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Go is case-sensitive. Based on the basic types explained in the previous chapter, there will be the following basic variable types − Sr.No Type & Description 1 byte Typically a single octet(one byte). This is an byte type. 2 int The most natural size of integer for the machine. 3 float32 A single-precision floating point value. Go programming language also allows to define various other types of variables such as Enumeration, Pointer, Array, Structure, and Union, which we will discuss in subsequent chapters. In this chapter, we will focus only basic variable types. Variable Definition in Go A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows − var variable_list optional_data_type; Here, optional_data_type is a valid Go data type including byte, int, float32, complex64, boolean or any user-defined object, etc., and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here − var i, j, k int; var c, ch byte; var f, salary float32; d = 42; The statement “var i, j, k;” declares and defines the variables i, j and k; which instructs the compiler to create variables named i, j, and k of type int. Variables can be initialized (assigned an initial value) in their declaration. The type of variable is automatically judged by the compiler based on the value passed to it. The initializer consists of an equal sign followed by a constant expression as follows − variable_name = value; For example, d = 3, f = 5; // declaration of d and f. Here d and f are int For definition without an initializer: variables with static storage duration are implicitly initialized with nil (all bytes have the value 0); the initial value of all other variables is zero value of their data type. Static Type Declaration in Go A static type variable declaration provides assurance to the compiler that there is one variable available with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail of the variable. A variable declaration has its meaning at the time of compilation only, the compiler needs the actual variable declaration at the time of linking of the program. Example Try the following example, where the variable has been declared with a type and initialized inside the main function − Live Demo package main import “fmt” func main() { var x float64 x = 20.0 fmt.Println(x) fmt.Printf(“x is of type %Tn”, x) } When the above code is compiled and executed, it produces the following result − 20 x is of type float64 Dynamic Type Declaration / Type Inference in Go A dynamic type variable declaration requires the compiler to interpret the type of the variable based on the value passed to it. The compiler does not require a variable to have type statically as a necessary requirement. Example Try the following example, where the variables have been declared without any type. Notice, in case of type inference, we initialized the variable y with := operator, whereas x is initialized using = operator. Live Demo package main import “fmt” func main() { var x float64 = 20.0 y := 42 fmt.Println(x) fmt.Println(y) fmt.Printf(“x is of type %Tn”, x) fmt.Printf(“y is of type %Tn”, y) } When the above code is compiled and executed, it produces the following result − 20 42 x is of type float64 y is of type int Mixed Variable Declaration in Go Variables of different types can be declared in one go using type inference. Example Live Demo package main import “fmt” func main() { var a, b, c = 3, 4, “foo” fmt.Println(a) fmt.Println(b) fmt.Println(c) fmt.Printf(“a is of type %Tn”, a) fmt.Printf(“b is of type %Tn”, b) fmt.Printf(“c is of type %Tn”, c) } When the above code is compiled and executed, it produces the following result − 3 4 foo a is of type int b is of type int c is of type string The lvalues and the rvalues in Go There are two kinds of expressions in Go − lvalue − Expressions that refer to a memory location is called “lvalue” expression. An lvalue may appear as either the left-hand or right-hand side of an assignment. rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment. Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side. The following statement is valid − x = 20.0 The following statement is not valid. It would generate compile-time error − 10 = 20 Print Page Previous Next Advertisements ”;

Go – Pointers

Go – Pointers ”; Previous Next Pointers in Go are easy and fun to learn. Some Go programming tasks are performed more easily with pointers, and other tasks, such as call by reference, cannot be performed without using pointers. So it becomes necessary to learn pointers to become a perfect Go programmer. As you know, every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory. Consider the following example, which will print the address of the variables defined − Live Demo package main import “fmt” func main() { var a int = 10 fmt.Printf(“Address of a variable: %xn”, &a ) } When the above code is compiled and executed, it produces the following result − Address of a variable: 10328000 So you understood what is memory address and how to access it. Now let us see what pointers are. What Are Pointers? A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address. The general form of a pointer variable declaration is − var var_name *var-type Here, type is the pointer”s base type; it must be a valid C data type and var-name is the name of the pointer variable. The asterisk * you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration − var ip *int /* pointer to an integer */ var fp *float32 /* pointer to a float */ The actual data type of the value of all pointers, whether integer, float, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to. How to Use Pointers? There are a few important operations, which we frequently perform with pointers: (a) we define pointer variables, (b) assign the address of a variable to a pointer, and (c) access the value at the address stored in the pointer variable. All these operations are carried out using the unary operator * that returns the value of the variable located at the address specified by its operand. The following example demonstrates how to perform these operations − Live Demo package main import “fmt” func main() { var a int = 20 /* actual variable declaration */ var ip *int /* pointer variable declaration */ ip = &a /* store address of a in pointer variable*/ fmt.Printf(“Address of a variable: %xn”, &a ) /* address stored in pointer variable */ fmt.Printf(“Address stored in ip variable: %xn”, ip ) /* access the value using the pointer */ fmt.Printf(“Value of *ip variable: %dn”, *ip ) } When the above code is compiled and executed, it produces the following result − Address of var variable: 10328000 Address stored in ip variable: 10328000 Value of *ip variable: 20 Nil Pointers in Go Go compiler assign a Nil value to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned nil is called a nil pointer. The nil pointer is a constant with a value of zero defined in several standard libraries. Consider the following program − Live Demo package main import “fmt” func main() { var ptr *int fmt.Printf(“The value of ptr is : %xn”, ptr ) } When the above code is compiled and executed, it produces the following result − The value of ptr is 0 On most of the operating systems, programs are not permitted to access memory at address 0 because that memory is reserved by the operating system. However, the memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location. But by convention, if a pointer contains the nil (zero) value, it is assumed to point to nothing. To check for a nil pointer you can use an if statement as follows − if(ptr != nil) /* succeeds if p is not nil */ if(ptr == nil) /* succeeds if p is null */ Go Pointers in Detail Pointers have many but easy concepts and they are very important to Go programming. The following concepts of pointers should be clear to a Go programmer − Sr.No Concept & Description 1 Go – Array of pointers You can define arrays to hold a number of pointers. 2 Go – Pointer to pointer Go allows you to have pointer on a pointer and so on. 3 Passing pointers to functions in Go Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function. Print Page Previous Next Advertisements ”;

Go – Data Types

Go – Data Types ”; Previous Next In the Go programming language, data types refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted. The types in Go can be classified as follows − Sr.No. Types and Description 1 Boolean types They are boolean types and consists of the two predefined constants: (a) true (b) false 2 Numeric types They are again arithmetic types and they represents a) integer types or b) floating point values throughout the program. 3 String types A string type represents the set of string values. Its value is a sequence of bytes. Strings are immutable types that is once created, it is not possible to change the contents of a string. The predeclared string type is string. 4 Derived types They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function types f) Slice types g) Interface types h) Map types i) Channel Types Array types and structure types are collectively referred to as aggregate types. The type of a function specifies the set of all functions with the same parameter and result types. We will discuss the basic types in the following section, whereas other types will be covered in the upcoming chapters. Integer Types The predefined architecture-independent integer types are − Sr.No. Types and Description 1 uint8 Unsigned 8-bit integers (0 to 255) 2 uint16 Unsigned 16-bit integers (0 to 65535) 3 uint32 Unsigned 32-bit integers (0 to 4294967295) 4 uint64 Unsigned 64-bit integers (0 to 18446744073709551615) 5 int8 Signed 8-bit integers (-128 to 127) 6 int16 Signed 16-bit integers (-32768 to 32767) 7 int32 Signed 32-bit integers (-2147483648 to 2147483647) 8 int64 Signed 64-bit integers (-9223372036854775808 to 9223372036854775807) Floating Types The predefined architecture-independent float types are − Sr.No. Types and Description 1 float32 IEEE-754 32-bit floating-point numbers 2 float64 IEEE-754 64-bit floating-point numbers 3 complex64 Complex numbers with float32 real and imaginary parts 4 complex128 Complex numbers with float64 real and imaginary parts The value of an n-bit integer is n bits and is represented using two”s complement arithmetic operations. Other Numeric Types There is also a set of numeric types with implementation-specific sizes − Sr.No. Types and Description 1 byte same as uint8 2 rune same as int32 3 uint 32 or 64 bits 4 int same size as uint 5 uintptr an unsigned integer to store the uninterpreted bits of a pointer value Print Page Previous Next Advertisements ”;

Go – Strings

Go – Strings ”; Previous Next Strings, which are widely used in Go programming, are a readonly slice of bytes. In the Go programming language, strings are slices. The Go platform provides various libraries to manipulate strings. unicode regexp strings Creating Strings The most direct way to create a string is to write − var greeting = “Hello world!” Whenever it encounters a string literal in your code, the compiler creates a string object with its value in this case, “Hello world!”. A string literal holds a valid UTF-8 sequences called runes. A String holds arbitrary bytes. Live Demo package main import “fmt” func main() { var greeting = “Hello world!” fmt.Printf(“normal string: “) fmt.Printf(“%s”, greeting) fmt.Printf(“n”) fmt.Printf(“hex bytes: “) for i := 0; i < len(greeting); i++ { fmt.Printf(“%x “, greeting[i]) } fmt.Printf(“n”) const sampleText = “xbdxb2x3dxbcx20xe2x8cx98” /*q flag escapes unprintable characters, with + flag it escapses non-ascii characters as well to make output unambigous */ fmt.Printf(“quoted string: “) fmt.Printf(“%+q”, sampleText) fmt.Printf(“n”) } This would produce the following result − normal string: Hello world! hex bytes: 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 quoted string: “xbdxb2=xbc u2318” Note − The string literal is immutable, so that once it is created a string literal cannot be changed. String Length len(str) method returns the number of bytes contained in the string literal. Live Demo package main import “fmt” func main() { var greeting = “Hello world!” fmt.Printf(“String Length is: “) fmt.Println(len(greeting)) } This would produce the following result − String Length is : 12 Concatenating Strings The strings package includes a method join for concatenating multiple strings − strings.Join(sample, ” “) Join concatenates the elements of an array to create a single string. Second parameter is seperator which is placed between element of the array. Let us look at the following example − package main import (“fmt” “math” )”fmt” “strings”) func main() { greetings := []string{“Hello”,”world!”} fmt.Println(strings.Join(greetings, ” “)) } This would produce the following result − Hello world! Print Page Previous Next Advertisements ”;

Go – Scope Rules

Go – Scope Rules ”; Previous Next A scope in any programming is a region of the program where a defined variable can exist and beyond that the variable cannot be accessed. There are three places where variables can be declared in Go programming language − Inside a function or a block (local variables) Outside of all functions (global variables) In the definition of function parameters (formal parameters) Let us find out what are local and global variables and what are formal parameters. Local Variables Variables that are declared inside a function or a block are called local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. The following example uses local variables. Here all the variables a, b, and c are local to the main() function. Live Demo package main import “fmt” func main() { /* local variable declaration */ var a, b, c int /* actual initialization */ a = 10 b = 20 c = a + b fmt.Printf (“value of a = %d, b = %d and c = %dn”, a, b, c) } When the above code is compiled and executed, it produces the following result − value of a = 10, b = 20 and c = 30 Global Variables Global variables are defined outside of a function, usually on top of the program. Global variables hold their value throughout the lifetime of the program and they can be accessed inside any of the functions defined for the program. A global variable can be accessed by any function. That is, a global variable is available for use throughout the program after its declaration. The following example uses both global and local variables − Live Demo package main import “fmt” /* global variable declaration */ var g int func main() { /* local variable declaration */ var a, b int /* actual initialization */ a = 10 b = 20 g = a + b fmt.Printf(“value of a = %d, b = %d and g = %dn”, a, b, g) } When the above code is compiled and executed, it produces the following result − value of a = 10, b = 20 and g = 30 A program can have the same name for local and global variables but the value of the local variable inside a function takes preference. For example − package main import “fmt” /* global variable declaration */ var g int = 20 func main() { /* local variable declaration */ var g int = 10 fmt.Printf (“value of g = %dn”, g) } When the above code is compiled and executed, it produces the following result − value of g = 10 Formal Parameters Formal parameters are treated as local variables with-in that function and they take preference over the global variables. For example − Live Demo package main import “fmt” /* global variable declaration */ var a int = 20; func main() { /* local variable declaration in main function */ var a int = 10 var b int = 20 var c int = 0 fmt.Printf(“value of a in main() = %dn”, a); c = sum( a, b); fmt.Printf(“value of c in main() = %dn”, c); } /* function to add two integers */ func sum(a, b int) int { fmt.Printf(“value of a in sum() = %dn”, a); fmt.Printf(“value of b in sum() = %dn”, b); return a + b; } When the above code is compiled and executed, it produces the following result − value of a in main() = 10 value of a in sum() = 10 value of b in sum() = 20 value of c in main() = 30 Initializing Local and Global Variables Local and global variables are initialized to their default value, which is 0; while pointers are initialized to nil. Data Type Initial Default Value int 0 float32 0 pointer nil Print Page Previous Next Advertisements ”;