make programmers more productive. Go is expressive, concise, clean, and efficient. Its concurrency mechanisms make it easy to write programs that get the most out of multicore and networked machines, while its novel type system enables flexible and modular program construction. Go compiles quickly to machine code yet has the convenience of garbage collection and the power of run- time reflection. It's a fast, statically typed, compiled language that feels like a dynamically typed, interpreted language
− •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.
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
of the two predefined constants: (a) true (b) false Numeric types They are again arithmetic types and they represents a) integer types or b) floating point values throughout the program. 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. 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
Unsigned 16-bit integers (0 to 65535) Uint32 Unsigned 32-bit integers (0 to 4294967295) Uint64 Unsigned 64-bit integers (0 to 18446744073709551615) Int8 Signed 8-bit integers (-128 to 127) Int16 Signed 16-bit integers (-32768 to 32767) Int32 Signed 32-bit integers (-2147483648 to 2147483647) Int64 Signed 64-bit integers (-9223372036854775808 to 9223372036854775807) Integer Types
Complex64 Complex numbers with float32 real and imaginary parts Complex128 Complex numbers with float64 real and imaginary parts Floating Types Number Types
operands - Subtracts second operand from the first * Multiplies both operands / Divides the numerator by the denominator. % Modulus operator; gives the remainder after an integer division. ++ Increment operator. It increases the integer value by one. -- Decrement operator. It decreases the integer value by one.
operands are equal or not; if yes, the condition becomes true. != It checks if the values of two operands are equal or not; if the values are not equal, then the condition becomes true. > It checks if the value of left operand is greater than the value of right operand; if yes, the condition becomes true. < It checks if the value of left operand is less than the value of the right operand; if yes, the condition becomes 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. <= 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. Relational Operators
operands are non- zero, then condition becomes true. || Called Logical OR Operator. If any of the two operands is non- zero, then condition becomes 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. Logical Operators
bit to the result if it exists in both operands. | Binary OR Operator copies a bit if it exists in either operand. ^ Binary XOR Operator copies the bit if it is set in one operand but not both. << Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. >> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.
-> . ++ - - Left to right Unary + - ! ~ ++ - - (type)* & sizeof Right to left Multiplicative * / % Left to right Additive + - Left to right Shift << >> Left to right Relational < <= > >= Left to right Equality == != Left to right Bitwise AND & Left to right Bitwise XOR ^ Left to right Bitwise OR | Left to right Logical AND && Left to right Logical OR || Left to right Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left Comma , Left to right
a boolean expression followed by one or more statements. if...else statement An if statement can be followed by an optional else statement, which executes when the boolean expression is false. nested if statementsYou can use one if or else if statement inside another if or else if statement(s). switch statementA switch statement allows a variable to be tested for equality against a list of values. select statementA select statement is similar to switch statement with difference that case statements refers to channel communications. If Else and Switch
statements multiple times and abbreviates the code that manages the loop variable. nested loopsThese are one or multiple loops inside any for loop. Loops
i++ { if i%2 != 0 { // skip odd numbers continue } sum += i } fmt.Println(sum) Continue and Break sum := 0 for i := 1; i < 5; i++ { if i%2 != 0 { // exit after first odd numbers break } sum += i } fmt.Println(sum)
body of the function } A function is a group of statements that together perform a task. Function •Func − It starts the declaration of a function. •Function Name − It is the actual name of the function. The function name and the parameter list together constitute the function signature. •Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. •Return Type − A function may return a list of values. The return_types is the list of data types of the values the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the not required. •Function Body − It contains a collection of statements that define what the function does.
var a int = 100 var b int = 200 var ret int /* calling a function to get max value */ ret = max(a, b) fmt.Printf( "Max value is : %d\n, ret ) } func max(num1, num2 int) int { var result int if (num1 > num2) { result = num1 } else { result = num2 } return result }
actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. Call by referenceThis method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument. Call Types
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)
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 = %d\n", a, b, c) } 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.
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 −
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 = %d\n", a, b, g) } func main() { /* local variable declaration */ var g int = 10 fmt.Printf ("value of g = %d\n", g) }
that function and they take preference over the global variables. For example − L 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() = %d\n", a); c = sum( a, b); fmt.Printf("value of c in main() = %d\n", c); } /* function to add two integers */ func sum(a, b int) int { fmt.Printf("value of a in sum() = %d\n", a); fmt.Printf("value of b in sum() = %d\n", b); return a + b; }
nil Initializing Local and Global Variables Local and global variables are initialized to their default value, which is 0; while pointers are initialized to nil.
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") } 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
in the string literal. package main import "fmt" func main() { var greeting = "Hello world!" fmt.Printf("String Length is: ") fmt.Println(len(greeting)) }
of the same type Declaring Arrays var balance [10] float32 var variable_name [SIZE] variable_type Initializing Arrays var balance = [5]float32{1000.0, 2.0, 3.4, 7.0, 50.0} var balance = []float32{1000.0, 2.0, 3.4, 7.0, 50.0}
main import "fmt“ func main() { var n [10]int /* n is an array of 10 integers */ var i,j int /* initialize elements of array n to 0 */ for i = 0; i < 10; i++ { n[i] = i + 100 /* set element at location i to i + 100 */ } /* output each array element's value */ for j = 0; j < 10; j++ { fmt.Printf("Element[%d] = %d\n", j, n[j] ) } }
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
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: %x\n", &a ) /* address stored in pointer variable */ fmt.Printf("Address stored in ip variable: %x\n", ip ) /* access the value using the pointer */ fmt.Printf("Value of *ip variable: %d\n", *ip ) }
arrays to hold a number of pointers. Go - Pointer to pointerGo allows you to have pointer on a pointer and so on. Passing pointers to functions in GoPassing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function. 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 −
which allows you to combine data items of different kinds. Defining a Structure Structures variable_name := structure_variable_type {value1, value2...valuen} type struct_variable_type struct { member definition; member definition; ... member definition; }
a function argument in very similar way as you pass any other variable or pointer func printBook( book Books ) { fmt.Printf( "Book title : %s\n", book.title); fmt.Printf( "Book author : %s\n", book.author); fmt.Printf( "Book subject : %s\n", book.subject); fmt.Printf( "Book book_id : %d\n", book.book_id); }
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 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*/
maps unique keys to values. A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key. Defining a Map You must use make function to create a map. var map_variable map[key_data_type]value_data_type map_variable = make(map[key_data_type]value_data_type)
countryCapitalMap = make(map[string]string) countryCapitalMap["France"] = "Paris" countryCapitalMap["Italy"] = "Rome" countryCapitalMap["Japan"] = "Tokyo“ countryCapitalMap["India"] = "New Delhi" for country := range countryCapitalMap { fmt.Println("Capital of",country,"is",countryCapitalMap[country]) } capital, ok := countryCapitalMap["United States"] if(ok){ fmt.Println("Capital of United States is", capital) } else { fmt.Println("Capital of United States is not present") } }
map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo","India":"New Delhi"} fmt.Println("Original map") for country := range countryCapitalMap { fmt.Println("Capital of",country,"is",countryCapitalMap[country]) } delete(countryCapitalMap,"France"); fmt.Println("Entry for France is deleted") fmt.Println("Updated map") for country := range countryCapitalMap { fmt.Println("Capital of",country,"is",countryCapitalMap[country]) } } Delete
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 func recursion() { recursion() /* function calls itself */ } func main() { recursion() }
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)) }
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)) } }
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 type_name(expression) 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 : %f\n",mean) }
represents a set of method signatures. The struct data type implements these interfaces to have method definitions for the method signature of the interfaces. /* define an interface */ type interface_name interface { method_name1 [return_type] method_name2 [return_type] method_name3 [return_type] ... method_namen [return_type] } /* define a struct */ type struct_name struct { /* variables */ } /* implement interface methods*/ func (struct_name_variable struct_name) method_name1() [return_type] { /* method implementation */ }
algorithms as defined in FIPS 180-4. package main import ( "crypto/sha256" "fmt" ) func main() { h := sha256.New() h.Write([]byte("hello world\n")) fmt.Printf("%x", h.Sum(nil)) }
SHA224 checksum. func Sum224(data []byte) (sum224 [Size224]byte) Sum224 returns the SHA224 checksum of the data. func Sum256(data []byte) [Size]byte Sum256 returns the SHA256 checksum of the data.
system functionality. The design is Unix-like, although the error handling is Go-like; failing calls return values of type error rather than error numbers. Often, more information is available within the error. For example, if a call that takes a file name fails, such as Open or Stat, the error will include the failing file name when printed and will be of type *PathError, which may be unpacked for more information. The os interface is intended to be uniform across all operating systems. Features not generally available appear in the system-specific package syscall. Here is a simple example, opening a file and reading some of it. file, err := os.Open("file.go") // For read access. if err != nil { log.Fatal(err) }
to the named directory. If there is an error, it will be of type *PathError. func Chmod(name string, mode FileMode) error Chmod changes the mode of the named file to mode. If the file is a symbolic link, it changes the mode of the link's target. If there is an error, it will be of type *PathError. func Chown(name string, uid, gid int) error Chown changes the numeric uid and gid of the named file func Chtimes(name string, atime time.Time, mtime time.Time) error Chtimes changes the access and modification times of the named file, similar to the Unix utime() or utimes() functions. func Clearenv() Clearenv deletes all environment variables.
of the named file. If the file is a symbolic link, It changes the size of the link's target. If there is an error, it will be of type *PathError. func Mkdir(name string, perm FileMode) error Mkdir creates a new directory with the specified name and permission bits (before umask). If there is an error, it will be of type *PathError. func Remove(name string) error Remove removes the named file or (empty) directory. If there is an error, it will be of type *PathError. func Setenv(key, value string) error Setenv sets the value of the environment variable named by the key. It returns an error, if any.
} func Create(name string) (*File, error) Create creates or truncates the named file. If the file already exists, it is truncated. I func NewFile(fd uintptr, name string) *File NewFile returns a new File with the given file descriptor and name. func Open(name string) (*File, error) Open opens the named file for reading func (f *File) Read(b []byte) (n int, err error) Read reads up to len(b) bytes from the File func (f *File) ReadAt(b []byte, off int64) (n int, err error) ReadAt reads len(b) bytes from the File starting at byte offset off. func (f *File) Truncate(size int64) error Truncate changes the size of the file. func (f *File) Write(b []byte) (n int, err error) Write writes len(b) bytes to the File.
DB libraries for Go. It is a full-featured object-relational mapping library for Golang. GORM is a developer-friendly tool for converting data between incompatible type systems. It is specially designed to minimize the rewritten codes when switching between type systems. GORM provides SQL builders, RAW SQL, auto migration tools, Extendable plugins for customization. All the features in GORM come with its own tests so that developers can easily try something new without borking the whole system. GEN Gen tool generates code for you. The tools help to generate type aware code in particular which tries to alleviate the gap of lacking templates in Golang. With no runtime magic, annotates your types with a special comment and generate source files.
on relational databases. In some organizations, modifying the DB schema is considered a daunting experience. Goose packages allow the developers to easily perform schema changes and data migrations if required. It works by versioning the schema, using migration files corresponding to each schema. The migrations files can be SQL or Go commands. cli cli is a simple and fast package for building command-line apps for Golang. It allows the developers to develop their own expressive command-line apps. cli is used for creating flags, bash-completion routines and generates help texts. cli is fast, fun and playful when you code for an API.
for Go related Microservice. This library offers specialized support for microservices. Go kit addresses the gap between functions such as RPC safety, infrastructure integration, system observability, and program design. It also provides guidance for building distributed systems with a solution to common problems. Vegeta is a tool used for HTTP load testing. This versatile tool was specially designed for testing HTTP services with a constant request rate. It works efficiently on analyzing the weak points of the program. Vegeta is one of the libraries that work throughout to improve the overall performance. It is presumably named after the Saiyan prince for its attack both targeted and distributed functions as a load tester.
web authentication system. This is an effective time-saver, it has several common authentication and authorization modules left for the developer’s choice. It is an easy way to integrate it, even without web frameworks and use it for fixing the bugs. 8. Glide Glide is a package manager for Go. Glides offer help to manage each program in its own vendor directory of package dependencies. It comes with the support of aliasing packages, versioning packages, support for custom local- global plugins, and easily manages and install-on-demand dependencies, resolves version differences and works with more tools.
method which executes independently and simultaneously in connection with any other Goroutines present in your program. Or in other words, every concurrently executing activity in Go language is known as a Goroutines. Thread: A process is a part of an operating system which is responsible for executing an application. Every program that executes on your system is a process and to run the code inside the application a process uses a term known as a thread. A thread is a lightweight process, or in other words, a thread is a unit which executes the code under the program. So every program has logic and a thread is responsible for executing this logic.
It wraps an io.Reader or io.Writer object, creating another object (Reader or Writer) that also implements the interface but provides buffering and some help for textual I/O.