1 2 3 4 5 6 | // Single line comment fmt.Println("Hello World!") // Comment at end of code /* Multi line comment that spans over mutliple lines */ |
1 2 3 4 5 6 7 8 9 | // Every language needs a Hello, World! package main import "fmt" func main() { fmt.Println("Hello, World!") } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // Variables // var variable_list optional_data_type; var i, j, k int; var c, ch byte; var f, salary float32; d = 42; f = 3, g = 4; var x float64 x = 20.45 var a, b, c = 3, 4, "foo" var x int = 30 // Static typed definition of int with value 30 y := 40 // Compiler infered type of int wiht value 40 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | // Integers byte // same as uint8 unit // 32 or 64 bits 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) uintptr // an unsigned integer to store the uninterpreted bits of a pointer value 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) rune // same as int32 int // same size as unit // Integer Literals 85 // decimal 0213 // octal 0x4b // hexadecimal 30 // int 30u // unsigned int 30l // long 30ul // unsigned long |
1 2 3 4 5 6 7 8 9 10 11 | // Floating Point Numbers 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 point literals 3.14159 // Legal 314159E-5L // Legal |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | // Strings "hello, dear" // A striing "hello, \ // A string over 2 lines dear" "hello, " "d" "ear" // Still a single string // Escape Sequences \\ // \ character \' // ' character \" // " character \? // ? character \a // Alert or bell \b // Backspace \f // Form feed \n // Newline \r // Carriage return \t // Horizontal tab \v // Vertical tab \ooo // Octal number of one to three digits \xhh . . . // Hexadecimal number of one or more digits // Assignment var greeting = "Hello world!" var greeting string = "Hello world!" greeting := "Hello world!" len(greeting) == 12 strings.Join("This, " and that") == "This and that" |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // Booleans var boolTrue bool = true var boolFalse bool = false otherBool := true var result bool var a bool s := "True" // s can be 1, True, TRUE, False, false, 0 etc a, _ = strconv.ParseBool(s) // observe that second value returned is ignored // here, because it returns true if it can be converted // else it resturns false var a string b := false a = strconv.FormatBool(b) |
1 2 3 4 5 6 | // Constants // const variable type = value; const LENGTH int = 10 const WIDTH int = 5 const SIZE = 20 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | // Arrays // Syntax // var variable_name [SIZE] variable_type // var variable_name [SIZE1][SIZE2]...[SIZEN] variable_type // Creation var balance [10] float32 var balance = []float32{1000.0, 2.0, 3.4, 7.0, 50.0} // Access & Modify balance[4] = 33.3 float32 salary = balance[4] salary == 33.3 // N Dimensional Array a = [3][4]int{ {0, 1, 2, 3} , /* initializers for row indexed by 0 */ {4, 5, 6, 7} , /* initializers for row indexed by 1 */ {8, 9, 10, 11} /* initializers for row indexed by 2 */ } int val = a[2][3] val == 11 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | // Slices var numbers []int /* a slice of unspecified size */ numbers == []int{0,0,0,0,0} numbers = make([]int,3,5) /* a slice of length 5 and capacity 5*/ numbers = [0, 0, 0] len(numbers) == 3 cap(numbers) == 5 var numbers []int // Nil initialized numbers == nil len(numbers) == 0 cap(numbers) == 0 numbers := []int{0,1,2,3,4,5,6,7,8} numbers[1:4] == [1, 2, 3] numbers[:3] == [0, 1, 2] numbers[4:] == [4, 5, 6, 7, 8] var numbers []int numbers = append(numbers, 0) // len = 1, cap = 2 numbers = append(numbers, 1) // len = 2, cap = 2 numbers = append(numbers, 2,3,4) // len = 5, cap = 8 numbers1 := make([]int, len(numbers), (cap(numbers))*2) copy(numbers1,numbers) // len = 5, cap = 16 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // Ranges numbers := []int{0,1,2,3,4,5,6,7,8} for i:= range numbers { fmt.Println("Slice item",i,"is",numbers[i]) } countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo"} for country := range countryCapitalMap { fmt.Println("Capital of",country,"is",countryCapitalMap[country]) } for country,capital := range countryCapitalMap { fmt.Println("Capital of",country,"is",capital) } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | // Maps // Syntax var map_variable map[key_data_type]value_data_type map_variable = make(map[key_data_type]value_data_type var countryCapitalMap map[string]string countryCapitalMap = make(map[string]string) countryCapitalMap["France"] = "Paris" countryCapitalMap["Italy"] = "Rome" countryCapitalMap["Japan"] = "Tokyo" countryCapitalMap["India"] = "New Delhi" // or countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo","India":"New Delhi"} for country := range countryCapitalMap { do_something(countryCapitalMap[country])) } capital, ok := countryCapitalMap["United States"] ok == true or false delete(countryCapitalMap,"France") |
1 2 3 4 5 6 7 8 9 10 | // Structures /* type struct_variable_type struct { member definition; member definition; ... member definition; } variable_name := structure_variable_type {value1, value2...valuen} */ |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | // 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 */ } ... func (struct_name_variable struct_name) method_namen() [return_type] { /* method implementation */ } // Example package main import ("fmt" "math") /* define an interface */ type Shape interface { area() float64 } /* define a circle */ type Circle struct { x,y,radius float64 } /* define a rectangle */ type Rectangle struct { width, height float64 } /* define a method for circle (implementation of Shape.area())*/ func(circle Circle) area() float64 { return math.Pi * circle.radius * circle.radius } /* define a method for rectangle (implementation of Shape.area())*/ func(rect Rectangle) area() float64 { return rect.width * rect.height } /* define a method for shape */ 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: %f\n",getArea(circle)) fmt.Printf("Rectangle area: %f\n",getArea(rectangle)) } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // Error Handling 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) } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | // Arithmetic operators + // 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 // Assignment operators = // Simple assignment operator, Assigns values from right side operands to left side operand += // Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand -= // Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand *= // Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand /= // Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand %= // Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand <<= // Left shift AND assignment operator >>= // Right shift AND assignment operator &= // Bitwise AND assignment operator ^= // bitwise exclusive OR and assignment operator |= // bitwise inclusive OR and assignment operator // Logical operators && // 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 // Relational Operators == // 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 // Bitwise operators & // Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12, which is 0000 1100 | // Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61, which is 0011 1101 ^ // Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) will give 49, which is 0011 0001 << // Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. >> // Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | // If condition if boolean_expression { /* statement(s) will execute if the boolean expression is true */ } if boolean_expression { /* statement(s) will execute if the boolean expression is true */ } else { /* statement(s) will execute if the boolean expression is false */ } if boolean_expression1 { /* Executes when the boolean expression 1 is true */ if boolean_expression2 { /* Executes when the boolean expression 2 is true */ } } // Assignment and comparison 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") } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | // Switch condition switch(boolean-expression or integral type){ case boolean-expression or integral type : statement(s); case boolean-expression or integral type : statement(s); /* you can have any number of case statements */ default : /* Optional */ statement(s); } select { case communication clause : statement(s); case communication clause : statement(s); /* you can have any number of case statements */ default : /* Optional */ statement(s); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | // Loops for [condition | ( init; condition; increment ) | Range] { statement(s); } for a := 0; a < 10; a++ { fmt.Printf("value of a: %d\n", a) } for a < b { a++ fmt.Printf("value of a: %d\n", a) } for i,x:= range numbers { fmt.Printf("value of x = %d at %d\n", x,i) } for true { // Infinite loop fmt.Printf("This loop will run forever.\n"); } // break for true { // Infinite loop if(something_happens()) { break // Exits the loop } do_something_elsde() } // continue for true { // Infinite loop if something_happens() { continue // next iteration of loop, skip everything } do_something_elsde() } // GOTO - Just don't use it |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | // Functions func function_name( [parameter list] ) [return_types] { body of the function } func add ( x int, y int ) int { return x + y } func add ( x, y int ) int { return x + y } func swap(x, y string) (string, string) { return y, x } a, b = swap("x", "y") |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | // Methods import "fmt" // Author structure type author struct { name string branch string particles int salary int } // Method with a receiver // of author type func (a author) show() { fmt.Println("Author's Name: ", a.name) fmt.Println("Branch Name: ", a.branch) fmt.Println("Published articles: ", a.particles) fmt.Println("Salary: ", a.salary) } // Main function func main() { // Initializing the values // of the author structure res := author{ name: "Sona", branch: "CSE", particles: 203, salary: 34000, } // Calling the method res.show() } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | // Pointers var ip *int // pointer to an integer var fp *float32 // pointer to a float var a int = 10 sp = &a // Assign the address of a to xip var b = *ip // Assign the value of a, pointer to by IP to b var ptr *int ptr == 0 // nil pointer if(ptr != nil) // succeeds if p is not nil if(ptr == nil) // succeeds if p is null var a int = 3000 var ptr *int var pptr **int /* take the address of var */ ptr = &a // Pointer ptr assigned the address or a *ptr == 3 pptr = &ptr // Pointer ptr assigned the address of ptr **pptr == 3 // Pass by reference func swap(x *int, y *int) { var temp int temp = *x /* save the value at address x */ *x = *y /* put y into x */ *y = temp /* put temp into y */ } x := 1 y := 2 swap (&x, &y) x == 2 y == 1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | // Error Handling // Error Interface type error interface { Error() string } // Create an error err = errors.New("Error: Something went wrong") // Use an error result, err:= some_function(x, y) // Returns result, err (nil if no error) if err != nil { handle_error(err) } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | // Packages package main // Import import "fmt" import ( "fmt" ) import ( "fmt" "time" "math" "math/rand" ) import "fmt" import "time" import "math" import "math/rand" // Package alias import ( str "Strings" ) // Create package go mod init inchkeithconsulting.com/something/mypackages inchkeithconsulting.com/something/mypackages/package1.go inchkeithconsulting.com/something/mypackages/subpackage/package2.go inchkeithconsulting.com/something/mypackages/subpackage/package3.go main.go import ( "fmt" str "strings" // Package Alias "inchkeithconsulting.com/something/mypackages/package1" "inchkeithconsulting.com/something/mypackages/subpackage/package2" "inchkeithconsulting.com/something/mypackages/subpackage/package3" ) // 3rd Party Packages import ( "fmt" "rsc.io/quote" // 3rd Party, go auto downloads ) // Manual Install go get -u github.com/jinzhu/gorm then import "github.com/jinzhu/gorm" |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | Create director Create file main.go with contents package main import "fmt" func main() { fmt.Println("Hello, World!") } go run main.go go mod init go build main.go |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | // Go Clean Code // Go Build Tools export GOPATH=$HOME/go export PATH=$PATH:$GOPATH/bin go install golang.org/x/tools/cmd/goimports@latest goimports -l -w . go fmt . // Requires .mod file go fmt <filename> go ver . // Requires .mod file go vet <filename> // Install is platform dependent, see https://golangci-lint.run/ golangci-lint golangci-lint run |
1 2 3 4 5 6 7 | // Go Keywords break default func interface select case defer go map struct chan else goto package switch const fallthrough if range type continue for import return var |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | // Go Standard Libraries archive bufio // Package bufio implements buffered I/O. builtin // Package builtin provides documentation for Go's predeclared identifiers. bytes // Package bytes implements functions for the manipulation of byte slices. compress container context // Package context defines the Context type, crypto // Package crypto collects common cryptographic constants. database debug embed // Package embed provides access to files embedded in the running Go program. encoding // Package encoding defines interfaces errors // Package errors implements functions to manipulate errors. expvar // Package expvar provides a standardized interface to public variables flag // Package flag implements command-line flag parsing. fmt // Package fmt implements formatted I/O with functions analogous to C's printf and scanf. go hash // Package hash provides interfaces for hash functions. html // Package html provides functions for escaping and unescaping HTML text. image // Package image implements a basic 2-D image library. index io // Package io provides basic interfaces to I/O primitives. log // Package log implements a simple logging package. math // Package math provides basic constants and mathematical functions. mime // Package mime implements parts of the MIME spec. net // Package net provides a portable interface for network I/O os // Package os provides a platform-independent interface to operating system functionality. path // Package path implements utility routines for manipulating slash-separated paths. plugin // Package plugin implements loading and symbol resolution of Go plugins. reflect // Package reflect implements run-time reflection, regexp // Package regexp implements regular expression search. runtime // Package runtime contains operations that interact with Go's runtime system sort // Package sort provides primitives for sorting slices and user-defined collections. strconv // Package implements conversions to and from string representations of basic data types. strings // Package strings implements simple functions to manipulate UTF-8 encoded strings. sync // Package sync provides basic synchronization primitives such as mutual exclusion locks. syscall // Package syscall contains an interface to the low-level operating system primitives. testing // Package testing provides support for automated testing of Go packages. text time // Package time provides functionality for measuring and displaying time. unicode // Package provides data and functions to test some properties of Unicode code points. unsafe // Package contains operations that step around the type safety of Go programs. internal |
1 | // Useful Go Libraries |