SlideShare une entreprise Scribd logo
1  sur  80
GoLang
Presented By -IXXO
The Go programming language is an open source project
to 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
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
Environment Setup
To set up your environment for Go programming
language, you need the following two software
available on your computer −
•A text editor
•Go compiler
To download pls visit :- https://golang.org/dl/
Hello World in Golang
package main
import "fmt"
func main() {
fmt.Println("Hello World")
}
Data Types
Boolean types
They are boolean types and
consists 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
Number Types
Uint8 Unsigned 8-bit integers (0 to 255)
Uint16 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
Float32 IEEE-754 32-bit floating-point numbers
Float64 IEEE-754 64-bit floating-point numbers
Complex64 Complex numbers with float32 real and imaginary parts
Complex128 Complex numbers with float64 real and imaginary parts
Floating Types
Number Types
Byte same as uint8
Rune same as int32
Uint 32 or 64 bits
Int same size as uint
Uintptr an unsigned integer to store the uninterpreted bits of a pointer value
Other Numeric Types
Derived types
• Pointer types
• Array types,
• Structure types,
• Union types and
• Function types
• Slice types
• Interface types
• Map types
• Channel Types
Go – Operators
Arithmetic Operators
Operator Description
+ Adds two 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.
Operator Description
== It checks if the values of two 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
Operator Description
&& Called Logical AND operator. If both the 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
Bitwise Operators
Operator Description
& Binary AND Operator copies a 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.
Operators Precedence in Go
Category Operator Associativity
Postfix () [] -> . ++ - - 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
Statement & Description
if statement An if statement consists of 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
package main
import "fmt"
func main() {
if 7%2 == 0 {
fmt.Println("7 is even")
}
else {
fmt.Println("7 is odd")
}
if num := 9; num < 0 {
fmt.Println(num, "is negative")
}
else if num < 10 {
fmt.Println(num, "has 1 digit")
}
else {
fmt.Println(num, "has multiple digits")
}
}
If Else - Example
package main
import (
"fmt"
"time"
)
func main() {
i := 2
fmt.Print("Write ", i, " as ")
switch i {
case 1:
fmt.Println("one")
case 2:
fmt.Println("two")
case 3:
fmt.Println("three")
}
}
Switch-Example
Loop Type & Description
for loopIt executes a sequence of statements multiple
times and abbreviates the code that manages the
loop variable.
nested loopsThese are one or multiple loops inside
any for loop.
Loops
Three-component loop
sum := 0
for i := 1; i < 5; i++ {
sum += i
}
fmt.Println(sum)
// 10 (1+2+3+4)
While loop
n := 1
for n < 5 {
n *= 2
}
fmt.Println(n)
// 8 (1*2*2*2)
For-each range loop
strings := []string{"hello", "world"}
// used a slice here
for i, s := range strings {
fmt.Println(i, s)
}
0 hello
1 world
sum := 0
for i := 1; i < 5; 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)
Defining a Function
func function_name( [parameter list] )
[return_types] { 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.
Example
/* function returning the max between two numbers */
func max(num1, num2 int) int {
/* local variable declaration */
result int if (num1 > num2) {
result = num1
}
else {
result = num2
}
return result
}
Calling a Function
package main
import "fmt"
func main() {
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 : %dn, ret )
}
func max(num1, num2 int) int {
var result int if (num1 > num2) {
result = num1
}
else {
result = num2
}
return result
}
Returning multiple values from Function
package main
import "fmt“
func swap(x, y string) (string, string)
{
return y, x
}
func main() {
a, b := swap("Mahesh", "Kumar")
fmt.Println(a, b)
}
Call Type & Description
Call by valueThis method copies the 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
Scope Rules
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)
Local Variables
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)
}
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.
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 −
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)
}
func main() {
/* local variable declaration */
var g int = 10
fmt.Printf ("value of g = %dn", g)
}
Formal Parameters
Formal parameters are treated as local variables with-in 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() = %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;
}
Data Type Initial Default Value
int 0
float32 0
pointer 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.
Strings
Liv
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")
}
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
String Length
len(str) method returns the number of bytes contained in the string literal.
package main
import "fmt"
func main() {
var greeting = "Hello world!"
fmt.Printf("String Length is: ")
fmt.Println(len(greeting))
}
package main
import ("fmt"
"strings")
func main() {
greetings := []string{"Hello","world!"}
fmt.Println(strings.Join(greetings, " "))
}
Concatenating Strings
Array
Array can store a fixed-size sequential collection of elements 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}
Accessing Array Elements
float32 salary = balance[9]
Live Demo
package 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] = %dn", j, n[j] )
} }
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
L
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 )
}
Concept & Description
Go - Array of pointersYou can define 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 −
Structure is another user-defined data type available in
Go programming, 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; }
package main
import "fmt"
type Books struct {
title string author string subject string book_id int }
func main() {
var Book1 Books
Book1.title = "Go Programming"
Book1.author = "Mahesh Kumar"
Book1.subject = "Go Programming Tutorial"
Book1.book_id = 6495407
fmt.Printf( "Book 1 author : %sn", Book1.author)
fmt.Printf( "Book 1 subject : %sn", Book1.subject)
fmt.Printf( "Book 1 book_id : %dn", Book1.book_id)
}
Structures as Function Arguments
You can pass a structure as a function argument in very similar way as you pass any other
variable or pointer
func printBook( book Books )
{
fmt.Printf( "Book title : %sn", book.title);
fmt.Printf( "Book author : %sn", book.author);
fmt.Printf( "Book subject : %sn", book.subject);
fmt.Printf( "Book book_id : %dn", book.book_id);
}
Pointers to Structures
struct_pointer.title;
struct_pointer = &Book
var struct_pointer *Books
Slices
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
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*/
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)
}
Subslicing
package main
import "fmt“
func main(){
numbers := []int{0,1,2,3,4,5,6,7,8}
printSlice(numbers)
fmt.Println("numbers ==", numbers)
fmt.Println("numbers[1:4] ==", numbers[1:4])
fmt.Println("numbers[:3] ==", numbers[:3])
fmt.Println("numbers[4:] ==", numbers[4:])
numbers1 := make([]int,0,5) printSlice(numbers1)
number2 := numbers[:2]
printSlice(number2)
number3 := numbers[2:5]
printSlice(number3)
}
func printSlice(x []int){
fmt.Printf("len = %d cap = %d slice = %vn", len(x), cap(x),x) }
append() and copy() Functions
package main
import "fmt“
func main() {
var numbers []int
printSlice(numbers)
numbers = append(numbers, 0)
printSlice(numbers)
numbers = append(numbers, 1)
printSlice(numbers)
numbers = append(numbers, 2,3,4)
printSlice(numbers)
numbers1 := make([]int, len(numbers),
(cap(numbers))*2)
copy(numbers1,numbers)
printSlice(numbers1) }
func printSlice(x []int){
fmt.Printf("len=%d cap=%d
slice=%vn",len(x),cap(x),x) }
Maps
Go provides another important data type named map which 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)
package main
import "fmt" func main() {
var countryCapitalMap map[string]string
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") }
}
Li
package main
import "fmt"
func main() {
countryCapitalMap := 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
Recursion
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
func recursion() {
recursion()
/* function calls itself */
}
func main() {
recursion()
}
Example 1: Calculating Factorial Using Recursion
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))
}
Example 2: Fibonacci Series Using Recursion
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))
}
}
Type Conversion
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
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 : %fn",mean)
}
Interfaces
Go programming provides another data type called interfaces which 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 */
}
Package main
import ("fmt" "math")
type Shape interface {
area() float64
}
type Circle struct {
x,y,radius float64
}
type Rectangle struct {
width, height float64
}
func(circle Circle) area() float64 { return math.Pi * circle.radius *
circle.radius }
func(rect Rectangle) area() float64 { return rect.width * rect.height
}
func getArea(shape Shape) float64 {
return shape.area()
}
func main() {
circle := Circle{x:0,y:0,radius:5}
rectangle := Rectangle {width:10, height:5}
fmt.Printf("Circle area: %fn",getArea(circle))
fmt.Printf("Rectangle area: %fn",getArea(rectangle)) }
Error Handling
Go programming provides a pretty simple error handling framework with inbuilt error interface type
of the following declaration
type error interface {
Error() string
}
func Sqrt(value float64)(float64, error) {
if(value < 0)
{
return 0, errors.New("Math: negative number passed to Sqrt")
}
return math.Sqrt(value), nil
}
result, err:= Sqrt(-1)
if err != nil {
fmt.Println(err)
}
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) } }
Some Important Packages
Package bufio implements buffered I/O. 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.
import "bufio"
Bufio
func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error)
func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error)
func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err
error)
type ReadWriter struct { *Reader *Writer }
func NewReadWriter(r *Reader, w *Writer) *ReadWriter
type Reader struct { // contains filtered or unexported fields }
func NewReader(rd io.Reader) *Reader
func (b *Reader) ReadByte() (byte, error)
func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error)
func (b *Reader) ReadSlice(delim byte) (line []byte, err error)
func (b *Reader) ReadString(delim byte) (string, error)
func (b *Reader) WriteTo(w io.Writer) (n int64, err error)
type Scanner struct { // contains filtered or unexported fields }
func NewScanner(r io.Reader) *Scanner
func (s *Scanner) Bytes() []byte
func (s *Scanner) Err() error
func (s *Scanner) Text() string
func NewScanner(r io.Reader) *Scanner
type Writer struct { // contains filtered or unexported fields }
func NewWriter(w io.Writer) *Writer
func NewWriterSize(w io.Writer, size int) *Writer
func (b *Writer) Available() int
func (b *Writer) ReadFrom(r io.Reader) (n int64, err error)
func (b *Writer) WriteByte(c byte) error
func (b *Writer) WriteString(s string) (int, error)
Package sha256
Package sha256 implements the SHA224 and SHA256
hash algorithms as defined in FIPS 180-4.
package main
import (
"crypto/sha256"
"fmt"
)
func main() {
h := sha256.New()
h.Write([]byte("hello worldn"))
fmt.Printf("%x", h.Sum(nil))
}
func New224() hash.Hash New224 returns a new hash.Hash computing the 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.
Package os
Package os provides a platform-independent interface to operating 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)
}
func Chdir(dir string) error
Chdir changes the current working directory 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.
Func Truncate(name string, size int64) error
Truncate changes the size 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.
type File struct { // contains filtered or unexported fields }
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.
Golang Libraries and Packages
GORM
GORM is the most popular 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.
Goose
Managing the schema is the primary task when working 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.
Go Kit
Go Kit is GitHub’s most popular standard library 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.
Authboss is a library for Go and also a modular 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.
package main
import (
"github.com/jinzhu/now"
"fmt"
)
func main() {
fmt.Println("All the beginnings...")
fmt.Println(now.BeginningOfMinute())
fmt.Println(now.BeginningOfHour())
fmt.Println(now.BeginningOfDay())
fmt.Println(now.BeginningOfWeek())
fmt.Println(now.BeginningOfMonth())
fmt.Println(now.BeginningOfQuarter())
fmt.Println(now.BeginningOfYear())
}
Output:
All the beginnings...
2017-06-04 16:59:00 -0700 PDT
2017-06-04 16:00:00 -0700 PDT
2017-06-04 00:00:00 -0700 PDT
2017-06-04 00:00:00 -0700 PDT
2017-06-01 00:00:00 -0700 PDT
2017-04-01 00:00:00 -0700 PDT
2016-12-31 23:00:00 -0800 PST
Goroutine vs Thread
Goroutine: A Goroutine is a function or 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.
Golang provides ‘go’ keyword to create goroutines.
When go keyword is placed before a function call, it becomes goroutines.
Some Important Packages
Bufio - Package bufio implements buffered I/O. 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.

Contenu connexe

Tendances (20)

Unit 7. Functions
Unit 7. FunctionsUnit 7. Functions
Unit 7. Functions
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
 
Python unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabusPython unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabus
 
Function in C program
Function in C programFunction in C program
Function in C program
 
85ec7 session2 c++
85ec7 session2 c++85ec7 session2 c++
85ec7 session2 c++
 
Recursion in c
Recursion in cRecursion in c
Recursion in c
 
User Defined Functions
User Defined FunctionsUser Defined Functions
User Defined Functions
 
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and Functions
 
Python advance
Python advancePython advance
Python advance
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & Import
 
Functions
FunctionsFunctions
Functions
 
Python unit 3 and Unit 4
Python unit 3 and Unit 4Python unit 3 and Unit 4
Python unit 3 and Unit 4
 
Python The basics
Python   The basicsPython   The basics
Python The basics
 
Control Structures in Python
Control Structures in PythonControl Structures in Python
Control Structures in Python
 
Unit 4. Operators and Expression
Unit 4. Operators and Expression  Unit 4. Operators and Expression
Unit 4. Operators and Expression
 
Pythonintro
PythonintroPythonintro
Pythonintro
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
What is c
What is cWhat is c
What is c
 
Python unit 2 M.sc cs
Python unit 2 M.sc csPython unit 2 M.sc cs
Python unit 2 M.sc cs
 
C functions
C functionsC functions
C functions
 

Similaire à GoLang - The Concise and Productive Programming Language

1_Python Basics.pdf
1_Python Basics.pdf1_Python Basics.pdf
1_Python Basics.pdfMaheshGour5
 
C language presentation
C language presentationC language presentation
C language presentationbainspreet
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteTushar B Kute
 
data type.pptxddddswwyertr hai na ki extend kr de la
data type.pptxddddswwyertr hai na ki extend kr de ladata type.pptxddddswwyertr hai na ki extend kr de la
data type.pptxddddswwyertr hai na ki extend kr de laLEOFAKE
 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxpriestmanmable
 
An introduction to functional programming with Swift
An introduction to functional programming with SwiftAn introduction to functional programming with Swift
An introduction to functional programming with SwiftFatih Nayebi, Ph.D.
 
modul-python-all.pptx
modul-python-all.pptxmodul-python-all.pptx
modul-python-all.pptxYusuf Ayuba
 
Python_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxPython_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxSahajShrimal1
 
User Defined Functions in C
User Defined Functions in CUser Defined Functions in C
User Defined Functions in CRAJ KUMAR
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysDevaKumari Vijay
 
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdfBasic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdfComputer Programmer
 
PE1 Module 2.ppt
PE1 Module 2.pptPE1 Module 2.ppt
PE1 Module 2.pptbalewayalew
 
B.sc CSIT 2nd semester C++ Unit2
B.sc CSIT  2nd semester C++ Unit2B.sc CSIT  2nd semester C++ Unit2
B.sc CSIT 2nd semester C++ Unit2Tekendra Nath Yogi
 

Similaire à GoLang - The Concise and Productive Programming Language (20)

1_Python Basics.pdf
1_Python Basics.pdf1_Python Basics.pdf
1_Python Basics.pdf
 
C language presentation
C language presentationC language presentation
C language presentation
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B Kute
 
data type.pptxddddswwyertr hai na ki extend kr de la
data type.pptxddddswwyertr hai na ki extend kr de ladata type.pptxddddswwyertr hai na ki extend kr de la
data type.pptxddddswwyertr hai na ki extend kr de la
 
Token and operators
Token and operatorsToken and operators
Token and operators
 
Basic commands in C++
Basic commands in C++Basic commands in C++
Basic commands in C++
 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
 
An introduction to functional programming with Swift
An introduction to functional programming with SwiftAn introduction to functional programming with Swift
An introduction to functional programming with Swift
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
modul-python-all.pptx
modul-python-all.pptxmodul-python-all.pptx
modul-python-all.pptx
 
C program
C programC program
C program
 
Python_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxPython_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptx
 
User Defined Functions in C
User Defined Functions in CUser Defined Functions in C
User Defined Functions in C
 
Vb script final pari
Vb script final pariVb script final pari
Vb script final pari
 
Python
PythonPython
Python
 
Operators1.pptx
Operators1.pptxOperators1.pptx
Operators1.pptx
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
 
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdfBasic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
 
PE1 Module 2.ppt
PE1 Module 2.pptPE1 Module 2.ppt
PE1 Module 2.ppt
 
B.sc CSIT 2nd semester C++ Unit2
B.sc CSIT  2nd semester C++ Unit2B.sc CSIT  2nd semester C++ Unit2
B.sc CSIT 2nd semester C++ Unit2
 

Dernier

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 

Dernier (20)

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 

GoLang - The Concise and Productive Programming Language

  • 2. The Go programming language is an open source project to 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
  • 3. 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.
  • 4. 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
  • 5. Environment Setup To set up your environment for Go programming language, you need the following two software available on your computer − •A text editor •Go compiler To download pls visit :- https://golang.org/dl/
  • 6. Hello World in Golang package main import "fmt" func main() { fmt.Println("Hello World") }
  • 7. Data Types Boolean types They are boolean types and consists 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
  • 8. Number Types Uint8 Unsigned 8-bit integers (0 to 255) Uint16 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
  • 9. Float32 IEEE-754 32-bit floating-point numbers Float64 IEEE-754 64-bit floating-point numbers Complex64 Complex numbers with float32 real and imaginary parts Complex128 Complex numbers with float64 real and imaginary parts Floating Types Number Types
  • 10. Byte same as uint8 Rune same as int32 Uint 32 or 64 bits Int same size as uint Uintptr an unsigned integer to store the uninterpreted bits of a pointer value Other Numeric Types
  • 11. Derived types • Pointer types • Array types, • Structure types, • Union types and • Function types • Slice types • Interface types • Map types • Channel Types
  • 12. Go – Operators Arithmetic Operators Operator Description + Adds two 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.
  • 13. Operator Description == It checks if the values of two 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
  • 14. Operator Description && Called Logical AND operator. If both the 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
  • 15. Bitwise Operators Operator Description & Binary AND Operator copies a 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.
  • 16. Operators Precedence in Go Category Operator Associativity Postfix () [] -> . ++ - - 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
  • 17. Statement & Description if statement An if statement consists of 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
  • 18. package main import "fmt" func main() { if 7%2 == 0 { fmt.Println("7 is even") } else { fmt.Println("7 is odd") } if num := 9; num < 0 { fmt.Println(num, "is negative") } else if num < 10 { fmt.Println(num, "has 1 digit") } else { fmt.Println(num, "has multiple digits") } } If Else - Example
  • 19. package main import ( "fmt" "time" ) func main() { i := 2 fmt.Print("Write ", i, " as ") switch i { case 1: fmt.Println("one") case 2: fmt.Println("two") case 3: fmt.Println("three") } } Switch-Example
  • 20. Loop Type & Description for loopIt executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. nested loopsThese are one or multiple loops inside any for loop. Loops
  • 21. Three-component loop sum := 0 for i := 1; i < 5; i++ { sum += i } fmt.Println(sum) // 10 (1+2+3+4)
  • 22. While loop n := 1 for n < 5 { n *= 2 } fmt.Println(n) // 8 (1*2*2*2)
  • 23. For-each range loop strings := []string{"hello", "world"} // used a slice here for i, s := range strings { fmt.Println(i, s) } 0 hello 1 world
  • 24. sum := 0 for i := 1; i < 5; 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)
  • 25. Defining a Function func function_name( [parameter list] ) [return_types] { 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.
  • 26. Example /* function returning the max between two numbers */ func max(num1, num2 int) int { /* local variable declaration */ result int if (num1 > num2) { result = num1 } else { result = num2 } return result }
  • 27. Calling a Function package main import "fmt" func main() { 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 : %dn, ret ) } func max(num1, num2 int) int { var result int if (num1 > num2) { result = num1 } else { result = num2 } return result }
  • 28. Returning multiple values from Function package main import "fmt“ func swap(x, y string) (string, string) { return y, x } func main() { a, b := swap("Mahesh", "Kumar") fmt.Println(a, b) }
  • 29. Call Type & Description Call by valueThis method copies the 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
  • 30. Scope Rules 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)
  • 31. Local Variables 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) } 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.
  • 32. 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 −
  • 33. 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) } func main() { /* local variable declaration */ var g int = 10 fmt.Printf ("value of g = %dn", g) }
  • 34. Formal Parameters Formal parameters are treated as local variables with-in 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() = %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; }
  • 35. Data Type Initial Default Value int 0 float32 0 pointer 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.
  • 36. Strings Liv 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") } 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
  • 37. String Length len(str) method returns the number of bytes contained in the string literal. package main import "fmt" func main() { var greeting = "Hello world!" fmt.Printf("String Length is: ") fmt.Println(len(greeting)) }
  • 38. package main import ("fmt" "strings") func main() { greetings := []string{"Hello","world!"} fmt.Println(strings.Join(greetings, " ")) } Concatenating Strings
  • 39. Array Array can store a fixed-size sequential collection of elements 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}
  • 40. Accessing Array Elements float32 salary = balance[9] Live Demo package 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] = %dn", j, n[j] ) } }
  • 41. 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
  • 42. L 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 ) }
  • 43. Concept & Description Go - Array of pointersYou can define 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 −
  • 44. Structure is another user-defined data type available in Go programming, 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; }
  • 45. package main import "fmt" type Books struct { title string author string subject string book_id int } func main() { var Book1 Books Book1.title = "Go Programming" Book1.author = "Mahesh Kumar" Book1.subject = "Go Programming Tutorial" Book1.book_id = 6495407 fmt.Printf( "Book 1 author : %sn", Book1.author) fmt.Printf( "Book 1 subject : %sn", Book1.subject) fmt.Printf( "Book 1 book_id : %dn", Book1.book_id) }
  • 46. Structures as Function Arguments You can pass a structure as a function argument in very similar way as you pass any other variable or pointer func printBook( book Books ) { fmt.Printf( "Book title : %sn", book.title); fmt.Printf( "Book author : %sn", book.author); fmt.Printf( "Book subject : %sn", book.subject); fmt.Printf( "Book book_id : %dn", book.book_id); }
  • 48. Slices 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 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*/
  • 49. 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) }
  • 50. Subslicing package main import "fmt“ func main(){ numbers := []int{0,1,2,3,4,5,6,7,8} printSlice(numbers) fmt.Println("numbers ==", numbers) fmt.Println("numbers[1:4] ==", numbers[1:4]) fmt.Println("numbers[:3] ==", numbers[:3]) fmt.Println("numbers[4:] ==", numbers[4:]) numbers1 := make([]int,0,5) printSlice(numbers1) number2 := numbers[:2] printSlice(number2) number3 := numbers[2:5] printSlice(number3) } func printSlice(x []int){ fmt.Printf("len = %d cap = %d slice = %vn", len(x), cap(x),x) }
  • 51. append() and copy() Functions package main import "fmt“ func main() { var numbers []int printSlice(numbers) numbers = append(numbers, 0) printSlice(numbers) numbers = append(numbers, 1) printSlice(numbers) numbers = append(numbers, 2,3,4) printSlice(numbers) numbers1 := make([]int, len(numbers), (cap(numbers))*2) copy(numbers1,numbers) printSlice(numbers1) } func printSlice(x []int){ fmt.Printf("len=%d cap=%d slice=%vn",len(x),cap(x),x) }
  • 52. Maps Go provides another important data type named map which 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)
  • 53. package main import "fmt" func main() { var countryCapitalMap map[string]string 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") } }
  • 54. Li package main import "fmt" func main() { countryCapitalMap := 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
  • 55. Recursion 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 func recursion() { recursion() /* function calls itself */ } func main() { recursion() }
  • 56. Example 1: Calculating Factorial Using Recursion 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)) }
  • 57. Example 2: Fibonacci Series Using Recursion 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)) } }
  • 58. Type Conversion 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 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 : %fn",mean) }
  • 59. Interfaces Go programming provides another data type called interfaces which 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 */ }
  • 60. Package main import ("fmt" "math") type Shape interface { area() float64 } type Circle struct { x,y,radius float64 } type Rectangle struct { width, height float64 } func(circle Circle) area() float64 { return math.Pi * circle.radius * circle.radius } func(rect Rectangle) area() float64 { return rect.width * rect.height } func getArea(shape Shape) float64 { return shape.area() } func main() { circle := Circle{x:0,y:0,radius:5} rectangle := Rectangle {width:10, height:5} fmt.Printf("Circle area: %fn",getArea(circle)) fmt.Printf("Rectangle area: %fn",getArea(rectangle)) }
  • 61. Error Handling Go programming provides a pretty simple error handling framework with inbuilt error interface type of the following declaration type error interface { Error() string } func Sqrt(value float64)(float64, error) { if(value < 0) { return 0, errors.New("Math: negative number passed to Sqrt") } return math.Sqrt(value), nil } result, err:= Sqrt(-1) if err != nil { fmt.Println(err) }
  • 62. 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) } }
  • 63. Some Important Packages Package bufio implements buffered I/O. 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. import "bufio" Bufio func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error) func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error) func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error)
  • 64. type ReadWriter struct { *Reader *Writer } func NewReadWriter(r *Reader, w *Writer) *ReadWriter type Reader struct { // contains filtered or unexported fields } func NewReader(rd io.Reader) *Reader func (b *Reader) ReadByte() (byte, error) func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error) func (b *Reader) ReadSlice(delim byte) (line []byte, err error) func (b *Reader) ReadString(delim byte) (string, error) func (b *Reader) WriteTo(w io.Writer) (n int64, err error)
  • 65. type Scanner struct { // contains filtered or unexported fields } func NewScanner(r io.Reader) *Scanner func (s *Scanner) Bytes() []byte func (s *Scanner) Err() error func (s *Scanner) Text() string func NewScanner(r io.Reader) *Scanner
  • 66. type Writer struct { // contains filtered or unexported fields } func NewWriter(w io.Writer) *Writer func NewWriterSize(w io.Writer, size int) *Writer func (b *Writer) Available() int func (b *Writer) ReadFrom(r io.Reader) (n int64, err error) func (b *Writer) WriteByte(c byte) error func (b *Writer) WriteString(s string) (int, error)
  • 67. Package sha256 Package sha256 implements the SHA224 and SHA256 hash algorithms as defined in FIPS 180-4. package main import ( "crypto/sha256" "fmt" ) func main() { h := sha256.New() h.Write([]byte("hello worldn")) fmt.Printf("%x", h.Sum(nil)) }
  • 68. func New224() hash.Hash New224 returns a new hash.Hash computing the 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.
  • 69. Package os Package os provides a platform-independent interface to operating 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) }
  • 70. func Chdir(dir string) error Chdir changes the current working directory 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.
  • 71. Func Truncate(name string, size int64) error Truncate changes the size 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.
  • 72. type File struct { // contains filtered or unexported fields } 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.
  • 73. Golang Libraries and Packages GORM GORM is the most popular 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.
  • 74. Goose Managing the schema is the primary task when working 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.
  • 75. Go Kit Go Kit is GitHub’s most popular standard library 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.
  • 76. Authboss is a library for Go and also a modular 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.
  • 77. package main import ( "github.com/jinzhu/now" "fmt" ) func main() { fmt.Println("All the beginnings...") fmt.Println(now.BeginningOfMinute()) fmt.Println(now.BeginningOfHour()) fmt.Println(now.BeginningOfDay()) fmt.Println(now.BeginningOfWeek()) fmt.Println(now.BeginningOfMonth()) fmt.Println(now.BeginningOfQuarter()) fmt.Println(now.BeginningOfYear()) } Output: All the beginnings... 2017-06-04 16:59:00 -0700 PDT 2017-06-04 16:00:00 -0700 PDT 2017-06-04 00:00:00 -0700 PDT 2017-06-04 00:00:00 -0700 PDT 2017-06-01 00:00:00 -0700 PDT 2017-04-01 00:00:00 -0700 PDT 2016-12-31 23:00:00 -0800 PST
  • 78. Goroutine vs Thread Goroutine: A Goroutine is a function or 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.
  • 79. Golang provides ‘go’ keyword to create goroutines. When go keyword is placed before a function call, it becomes goroutines.
  • 80. Some Important Packages Bufio - Package bufio implements buffered I/O. 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.