├── .gitignore ├── 1_Introduction ├── CMD1.go ├── CMD2.go ├── CMD3.go ├── HelloWorld.go └── Time.go ├── 2_ProgramStructure ├── CodeLocation.go ├── Export.go ├── FuncMultiReturn.go ├── FuncNamedReturn.go ├── Functions.go ├── Import.go ├── Miscellaneous.go ├── Printf.go ├── ShortVariableDec.go ├── StructCBR.go ├── StructCBV.go ├── Var.go ├── VariableFunc.go ├── const.go ├── const2.go └── constFunc.go ├── 3_Types ├── BuiltIn.go ├── CompositionAttribute.go ├── CompositionInterface1.go ├── CompositionInterface2.go ├── CompositionMethod.go ├── StructDeclaration.go ├── StructDot.go ├── StructNew.go ├── StructSubsetPrint.go └── TypeConversion.go ├── 4_Collections ├── ArrayMulti.go ├── ArrayPrint.go ├── Arrays.go ├── Map1Literal.go ├── Map2Make.go ├── Map3Mutation.go ├── Map4Range.go ├── Map5WordCount.go ├── Slice1Create.go ├── Slice2Slicing.go ├── Slice3Reference.go ├── Slice4Append.go ├── Slice5Len.go ├── Slice6Nil.go └── Slice7Range.go ├── 5_ControlFlow ├── CharFrequency.go ├── Exercise1.go ├── For.go ├── If.go ├── InfiniteForOSTime.go ├── Switch.go └── WordBreak.go ├── 6_Methods ├── CodeOrganization.go ├── CodeOrganization2.go ├── MethodReceiverPointers.go ├── MethodStruct.go └── TypeAlias.go ├── LICENSE ├── README.md └── docs └── cover.gif /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | # vendor/ 16 | -------------------------------------------------------------------------------- /1_Introduction/CMD1.go: -------------------------------------------------------------------------------- 1 | // Command Line Arguments with conventional for loop 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | "os" 7 | ) 8 | 9 | func main() { 10 | var str, seperator string 11 | for i := 1; i < len(os.Args); i++ { 12 | str += seperator + os.Args[i] 13 | seperator = " " 14 | } 15 | fmt.Println(str) 16 | } 17 | -------------------------------------------------------------------------------- /1_Introduction/CMD2.go: -------------------------------------------------------------------------------- 1 | // Command Line Arguments with variable iterator loop 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | "os" 7 | ) 8 | 9 | func main() { 10 | str, seperator := "", "" 11 | for _, args := range os.Args[1:] { 12 | str += seperator + args 13 | seperator = " " 14 | } 15 | fmt.Println(str) 16 | } 17 | -------------------------------------------------------------------------------- /1_Introduction/CMD3.go: -------------------------------------------------------------------------------- 1 | // using the string function 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | "os" 7 | "strings" 8 | ) 9 | 10 | func main() { 11 | fmt.Println(strings.Join(os.Args[1:]," ")) 12 | fmt.Println(os.Args[1:]) //unformatted 13 | } 14 | -------------------------------------------------------------------------------- /1_Introduction/HelloWorld.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println("Hello, World!") 7 | } 8 | -------------------------------------------------------------------------------- /1_Introduction/Time.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | func main() { 9 | start := time.Now() 10 | end := time.Since(start).Seconds() 11 | fmt.Println(end) 12 | } 13 | -------------------------------------------------------------------------------- /2_ProgramStructure/CodeLocation.go: -------------------------------------------------------------------------------- 1 | // Fetch Go code from online repositories via URL - $ go get github.com/mattetti/goRailsYourself/crypto 2 | // Import library into local Go program - import "github.com/mattetti/goRailsYourself/crypto" 3 | // See location of GOPATH - $ echo $GOPATH 4 | // See content of GOPATH -$ ls $GOPATH 5 | -------------------------------------------------------------------------------- /2_ProgramStructure/Export.go: -------------------------------------------------------------------------------- 1 | // In Go, a name is exported if it begins with a capital letter 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | "math" 7 | "net/http" 8 | ) 9 | 10 | func main() { 11 | fmt.Println(math.Pi) //uppercase name 12 | fmt.Printf("HTTP Status OK Code is %d\n",http.StatusOK) 13 | } 14 | -------------------------------------------------------------------------------- /2_ProgramStructure/FuncMultiReturn.go: -------------------------------------------------------------------------------- 1 | // Go allows returning multiple values 2 | package main 3 | 4 | import "fmt" 5 | 6 | // Generic function with no arguments 7 | func Generic() (string, string) { 8 | return "Nishkarsh", "Raj" 9 | } 10 | 11 | func main() { 12 | // declaring two variables with same function call 13 | fName, lName := Generic() 14 | fmt.Printf("My name is %s %s\n", fName, lName) 15 | } 16 | -------------------------------------------------------------------------------- /2_ProgramStructure/FuncNamedReturn.go: -------------------------------------------------------------------------------- 1 | // If no explicit return for variable specified, the current (if no current then default) value is returned 2 | package main 3 | 4 | import "fmt" 5 | 6 | func Generic() (Name, Empty string) { 7 | //Updating Name 8 | Name = "Nishkarsh" 9 | return // returns Nishkash and Empty String 10 | } 11 | 12 | func main() { 13 | name, empty := Generic() 14 | fmt.Println(empty + " " + name) 15 | } 16 | -------------------------------------------------------------------------------- /2_ProgramStructure/Functions.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // function to multiply two numbers // (x,y int) is also fine 6 | func Multiply(x int, y int) int { 7 | return x * y 8 | } 9 | 10 | func main() { 11 | fmt.Println(Multiply(5, 2)) 12 | } 13 | -------------------------------------------------------------------------------- /2_ProgramStructure/Import.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math/rand" 6 | "math" 7 | ) 8 | 9 | func main() { 10 | fmt.Println("My favorite number is", rand.Intn(41)) 11 | fmt.Printf("Square root of 5 = %g\n",math.Sqrt(5)) 12 | } 13 | -------------------------------------------------------------------------------- /2_ProgramStructure/Miscellaneous.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | ) 7 | 8 | func main() { 9 | // Declaration of multiple variables with single inbuilt function 10 | name, err := os.Open("/username") 11 | fmt.Println(name) 12 | fmt.Println(err) //nil 13 | 14 | // Swapping values like Python 15 | i, j := 0, 100 16 | i, j = j, i 17 | fmt.Println(i) //100 18 | fmt.Println(j) //0 19 | } 20 | -------------------------------------------------------------------------------- /2_ProgramStructure/Printf.go: -------------------------------------------------------------------------------- 1 | package main 2 | import "fmt" 3 | 4 | func main() { 5 | name := "Caprica-Six" 6 | aka := fmt.Sprintf("Number %d", 6) 7 | fmt.Printf("%s is also known as %s", 8 | name, aka) //printing variables within the string 9 | } 10 | -------------------------------------------------------------------------------- /2_ProgramStructure/ShortVariableDec.go: -------------------------------------------------------------------------------- 1 | package main 2 | import "fmt" 3 | 4 | func main() { 5 | name, location := "Prince Oberyn", "Dorne" 6 | age := 32 7 | fmt.Printf("%s age %d from %s ", name, age, location) 8 | } 9 | -------------------------------------------------------------------------------- /2_ProgramStructure/StructCBR.go: -------------------------------------------------------------------------------- 1 | // Call by reference - mutability 2 | package main 3 | import "fmt" 4 | 5 | type Artist struct { 6 | Name, Genre string 7 | Songs int 8 | } 9 | 10 | func newRelease(a *Artist) int { //passing an Artist by reference 11 | a.Songs++ 12 | return a.Songs 13 | } 14 | 15 | func main() { 16 | me := &Artist{Name: "Matt", Genre: "Electro", Songs: 42} 17 | fmt.Printf("%s released their %dth song\n", me.Name, newRelease(me)) 18 | fmt.Printf("%s has a total of %d songs", me.Name, me.Songs) 19 | } 20 | -------------------------------------------------------------------------------- /2_ProgramStructure/StructCBV.go: -------------------------------------------------------------------------------- 1 | // Call by value - Default - No mutation to original values 2 | package main 3 | import "fmt" 4 | 5 | type Artist struct { 6 | Name, Genre string 7 | Songs int 8 | } 9 | 10 | func newRelease(a Artist) int { //passing an Artist by value 11 | a.Songs++ 12 | return a.Songs 13 | } 14 | 15 | func main() { 16 | me := Artist{Name: "Matt", Genre: "Electro", Songs: 42} 17 | fmt.Printf("%s released their %dth song\n", me.Name, newRelease(me)) 18 | fmt.Printf("%s has a total of %d songs", me.Name, me.Songs) 19 | } 20 | -------------------------------------------------------------------------------- /2_ProgramStructure/Var.go: -------------------------------------------------------------------------------- 1 | package main 2 | import "fmt" 3 | 4 | func main() { 5 | // Multiple variable declaration/initialization with same var 6 | var ( 7 | name = "Nishkarsh Raj" 8 | SAP = 500060720 9 | ) 10 | fmt.Printf("Hello, my name is %s and My SAP ID is %d \n",name,SAP) 11 | } 12 | -------------------------------------------------------------------------------- /2_ProgramStructure/VariableFunc.go: -------------------------------------------------------------------------------- 1 | package main 2 | import "fmt" 3 | 4 | func main() { 5 | // creating a variable which stores a function 6 | nish := func() { 7 | fmt.Println("Hello, World!") 8 | } 9 | nish() 10 | nish() 11 | nish() 12 | } 13 | -------------------------------------------------------------------------------- /2_ProgramStructure/const.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | //package level const declaration 6 | const tempF = 312 7 | 8 | func main() { 9 | 10 | var tC, tF float64 11 | tF = tempF 12 | tC = (tF - 32) * 5 / 9 13 | 14 | //Note: Printf works for C like print statements not println 15 | fmt.Printf("Temperature in Farenhite is %g and in Celcius, it is %g\n", tF, tC) 16 | 17 | } 18 | -------------------------------------------------------------------------------- /2_ProgramStructure/const2.go: -------------------------------------------------------------------------------- 1 | package main 2 | import "fmt" 3 | 4 | const ( 5 | Pi = 3.14 6 | Truth = false 7 | Big = 1 << 62 8 | ) 9 | const ( 10 | StatusOK = 200 11 | StatusCreated = 201 12 | StatusAccepted = 202 13 | StatusNonAuthoritativeInfo = 203 14 | StatusNoContent = 204 15 | StatusResetContent = 205 16 | StatusPartialContent = 206 17 | ) 18 | 19 | const Greeting = "ハローワールド" //declaring a constant 20 | 21 | func main() { 22 | 23 | fmt.Println(Greeting) 24 | fmt.Println(Pi) 25 | fmt.Println(Truth) 26 | fmt.Println(Big) 27 | } 28 | -------------------------------------------------------------------------------- /2_ProgramStructure/constFunc.go: -------------------------------------------------------------------------------- 1 | package main 2 | import "fmt" 3 | 4 | // const declaration 5 | const freeze, boil = 0,100 // multideclaration must be comma seperated, cannot do like C - declare one then comma 6 | 7 | // user defined function - can be written before or after main 8 | // must specify the type of argument and return type explicitly 9 | func CtoF(cel float64) float64{ 10 | return ((9*cel + 160)/5) 11 | } 12 | 13 | // driver code 14 | func main() { 15 | fmt.Printf("Freezing Point of Water = %g\n",CtoF(freeze)) 16 | fmt.Printf("Boiling Point of Water = %g\n",CtoF(boil)) 17 | } 18 | -------------------------------------------------------------------------------- /3_Types/BuiltIn.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math/cmplx" 6 | ) 7 | 8 | var ( 9 | goIsFun bool = true //declaring a variable of type bool 10 | maxInt uint64 = 1<<64 - 1 //declaring a variable of type uint64 - maximum value for uint64 11 | complex complex128 = cmplx.Sqrt(-5 + 12i) //declaring a variable of type complex128 12 | ) 13 | 14 | func main() { 15 | const f = "%T(%v)\n" // format stored %T - type %v - value 16 | fmt.Printf(f, goIsFun, goIsFun) 17 | fmt.Printf(f, maxInt, maxInt) 18 | fmt.Printf(f, complex, complex) 19 | } 20 | -------------------------------------------------------------------------------- /3_Types/CompositionAttribute.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // Base struct 6 | type person struct { 7 | fName, lName string 8 | age int 9 | } 10 | 11 | // child struct - composition rather than inheritance 12 | type player struct { 13 | // every player is a person 14 | person 15 | pid string 16 | } 17 | 18 | func main() { 19 | 20 | // two ways to declare persons 21 | 22 | // 1. Dot Notation 23 | nish := player{} 24 | nish.fName = "Nishkarsh" 25 | nish.lName = "Raj" 26 | nish.age = 21 27 | nish.pid = "R41" 28 | fmt.Println(nish) 29 | 30 | // 2. Sub set type declaration 31 | obj := player{ 32 | person{fName: "First", lName: "Last", age: 20}, 33 | "RXX", 34 | } 35 | //fmt.Println(obj) 36 | //%+v shows field + value 37 | fmt.Printf("%+v", obj) 38 | } 39 | -------------------------------------------------------------------------------- /3_Types/CompositionInterface1.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "os" 6 | ) 7 | 8 | type Job struct { 9 | Command string 10 | Logger *log.Logger 11 | } 12 | 13 | func main() { 14 | job := &Job{"demo", log.New(os.Stdout, "Job: ", log.Ldate)} 15 | // same as 16 | // job := &Job{Command: "demo", 17 | // Logger: log.New(os.Stderr, "Job: ", log.Ldate)} 18 | job.Logger.Print("test") 19 | } 20 | -------------------------------------------------------------------------------- /3_Types/CompositionInterface2.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "os" 6 | ) 7 | 8 | type Job struct { 9 | Command string 10 | *log.Logger 11 | } 12 | 13 | func main() { 14 | job := &Job{"demo", log.New(os.Stdout, "Job: ", log.Ldate)} 15 | job.Print("starting now...") 16 | } 17 | -------------------------------------------------------------------------------- /3_Types/CompositionMethod.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // Base struct 6 | type person struct { 7 | fName, lName string 8 | age int 9 | } 10 | 11 | // Creating method for the structure 12 | // format - func (obj *struct_name) funcname(attributes) return type 13 | func (p *person) Hello() string { 14 | //sprintf function stores and returns but does not print to console 15 | return fmt.Sprintf("Hello, %s %s. How are you?\n", p.fName, p.lName) 16 | } 17 | 18 | // child struct 19 | type player struct { 20 | person 21 | pid string 22 | } 23 | 24 | func main() { 25 | obj := player{} 26 | obj.fName = "Nishkarsh" 27 | obj.lName = "Raj" 28 | fmt.Println(obj.Hello()) 29 | } 30 | -------------------------------------------------------------------------------- /3_Types/StructDeclaration.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type Point struct { 6 | x, y int 7 | } 8 | 9 | func main() { 10 | // Declaration of structures 11 | obj1 := Point{5, 2} // Implicit if all parameters specified 12 | obj2 := &Point{5, 2} // Pointer Reference 13 | obj3 := Point{x: 5} // y = 0 14 | obj4 := Point{} // All values set to type default 15 | fmt.Println(obj1, obj2, obj3, obj4) 16 | } 17 | -------------------------------------------------------------------------------- /3_Types/StructDot.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type Student struct { 6 | name, roll string 7 | sap int 8 | } 9 | 10 | func main() { 11 | nishkarsh := Student{name: "Nishkarsh Raj Khare", roll: "R171217041"} 12 | nishkarsh.sap = 500060720 13 | fmt.Println(nishkarsh) 14 | } 15 | -------------------------------------------------------------------------------- /3_Types/StructNew.go: -------------------------------------------------------------------------------- 1 | // new keyword in Go - initialize to default value of type and return pointer 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | ) 8 | 9 | type Bootcamp struct { 10 | Lat float64 11 | Lon float64 12 | } 13 | 14 | func main() { 15 | x := new(Bootcamp) 16 | y := &Bootcamp{} 17 | fmt.Println(*x == *y) 18 | } 19 | -------------------------------------------------------------------------------- /3_Types/StructSubsetPrint.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type Student struct { 6 | name string 7 | sap int 8 | roll string 9 | branch string 10 | } 11 | 12 | func main() { 13 | // print subset without declaration - generic 14 | fmt.Println(Student{name: "Nishkarsh Raj", sap: 500060720}) // named declaration - key value pair 15 | } 16 | -------------------------------------------------------------------------------- /3_Types/TypeConversion.go: -------------------------------------------------------------------------------- 1 | // Go follows explicit only type conversion else error. 2 | // Convert follows - type(value) 3 | 4 | package main 5 | 6 | import "fmt" 7 | 8 | func main() { 9 | x := 41 10 | u := uint8(x) 11 | f := float32(x) 12 | const format = "%T(%v)\n" 13 | 14 | fmt.Printf(format, x, x) 15 | fmt.Printf(format, u, u) 16 | fmt.Printf(format, f, f) 17 | } 18 | -------------------------------------------------------------------------------- /4_Collections/ArrayMulti.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var matrix [3][3]int 7 | for i := 0; i < 3; i++ { 8 | for j := 0; j < 3; j++ { 9 | matrix[i][j] = i + j 10 | } 11 | } 12 | 13 | //fmt.Println(matrix) 14 | 15 | for i := 0; i < 3; i++ { 16 | fmt.Println(matrix[i]) 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /4_Collections/ArrayPrint.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | nish := [...]string{"Nishkarsh", "Raj", "Khare"} 7 | 8 | // Print string as list 9 | fmt.Println(nish) 10 | 11 | // Print Quoted string 12 | fmt.Printf("%q\n", nish) 13 | 14 | // Print string as list 15 | fmt.Printf("%s\n", nish) 16 | } 17 | -------------------------------------------------------------------------------- /4_Collections/Arrays.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | // Var declaration 7 | var hello [2]string 8 | hello[0] = "Hello," 9 | hello[1] = "World!" 10 | fmt.Println(hello) 11 | 12 | // Shorthand Declaration 13 | odd := [5]int{1, 3, 5, 7, 9} 14 | fmt.Println(odd) 15 | 16 | // Implicit Size Declaration 17 | nish := [...]int{5, 2, 52, 4, 421, 4, 21, 5, 12} 18 | fmt.Println(nish) 19 | } 20 | -------------------------------------------------------------------------------- /4_Collections/Map1Literal.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | // literal declaration - map initialized when declared 7 | // syntax - map[key]value{} 8 | nish := map[string]int{ 9 | "Nishkarsh": 500060720, 10 | "Karan": 500060911, 11 | "Manthan": 500060128, 12 | "Rishabh": 500060226, // last element must also follow a comma 13 | } 14 | 15 | fmt.Println(nish) // automatically sorts dictionary because they are lexicographic 16 | fmt.Printf("%#v", nish) 17 | 18 | } 19 | -------------------------------------------------------------------------------- /4_Collections/Map2Make.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // structure 6 | type Points struct { 7 | x, y int 8 | } 9 | 10 | func main() { 11 | 12 | // Simple Map 13 | var m map[string]int 14 | //Empty map cannot be assigned - define space using make (not new) 15 | m = make(map[string]int) 16 | m["Nishkarsh"] = 500060720 17 | fmt.Println(m) 18 | 19 | // Complex Map 20 | var m2 map[string]Points 21 | m2 = make(map[string]Points) 22 | // m2["A"] = {2,5} //Implicit only allowed for literal declaration 23 | m2["B"] = Points{3, 10} //Explicit 24 | fmt.Println(m2) 25 | } 26 | -------------------------------------------------------------------------------- /4_Collections/Map3Mutation.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type Points struct { 6 | x, y int 7 | } 8 | 9 | func main() { 10 | // literal declaration with implicit definition for structures 11 | m := map[string]Points{ 12 | "A": {2, 4}, 13 | "B": {5, 2}, 14 | "C": {10, 8}, 15 | } 16 | fmt.Println(m) 17 | 18 | // 1. Insertion - New declaration without literal requires type specification 19 | // m["Origin"] = {0,0} 20 | m["Origin"] = Points{0, 0} 21 | fmt.Println(m) 22 | 23 | // 2. Update 24 | m["A"] = Points{2, 5} 25 | fmt.Println(m) 26 | 27 | // 3. Retrieval 28 | fmt.Println(m["Origin"]) 29 | 30 | // 4. delete 31 | delete(m, "Origin") 32 | fmt.Println(m) 33 | 34 | // 5. Existence - (value, presence) if present - print value | if absent print default type value 35 | v, p := m["Origin"] 36 | fmt.Printf("%t %v", p, v) 37 | v, p = m["A"] 38 | fmt.Printf("%t %v", p, v) 39 | 40 | } 41 | -------------------------------------------------------------------------------- /4_Collections/Map4Range.go: -------------------------------------------------------------------------------- 1 | // Range for Map returns key, value 2 | package main 3 | 4 | import "fmt" 5 | 6 | func main() { 7 | student := map[string]int{ 8 | "Nishkarsh": 500060720, 9 | "Karan": 500060911, 10 | "Manthan": 500060128, 11 | "Rishabh": 500060226, 12 | } 13 | 14 | for key, value := range student { 15 | fmt.Printf("Student %s's SAP is %d\n", key, value) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /4_Collections/Map5WordCount.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | func WordCount(s string) map[string]int { 9 | words := strings.Fields(s) // converts string into list of string broken by space 10 | count := map[string]int{} // Non-Empty Literal declaration 11 | for _, word := range words { 12 | count[word]++ 13 | } 14 | return count 15 | } 16 | 17 | func main() { 18 | fmt.Println(WordCount("As long As you Love me!")) //case sensitive - As not equals as 19 | } 20 | -------------------------------------------------------------------------------- /4_Collections/Slice1Create.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | 7 | // Way 1: Slice Literal - Initialize when declared by passing values 8 | nish1 := []string{"Nishkarsh", "Raj", "Khare"} 9 | fmt.Println(nish1) 10 | 11 | // Way 2: Make function - Declare with an initial size 12 | nish2 := make([]string, 3) 13 | nish2[0] = "Nishkarsh" 14 | nish2[1] = "Raj" 15 | nish2[2] = "Khare" 16 | fmt.Println(nish2) 17 | } 18 | -------------------------------------------------------------------------------- /4_Collections/Slice2Slicing.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | // Slices can be made up of Arrays as well 7 | array := [5]int{1, 3, 5, 7, 9} 8 | 9 | // Slices of Slice [lo:hi] are from lo to hi-1 inclusive similar to python and by default lo = 0 and hi = len 10 | fmt.Println(array[2:4]) 11 | fmt.Println(array[2:2]) //Nil slice 12 | } 13 | -------------------------------------------------------------------------------- /4_Collections/Slice3Reference.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | array := [5]int{1, 3, 5, 7, 9} 7 | 8 | // Slices are references to arrays - If multiple slice point to same array - Changes to one slice affects all 9 | sl1 := array[0:3] 10 | sl2 := array[2:4] //Share element 2 with slice 1 we will update that later 11 | 12 | fmt.Println(sl1, sl2) 13 | 14 | //array[2] == sl2[0] 15 | sl2[0] = 41 16 | fmt.Println(sl1, sl2) 17 | } 18 | -------------------------------------------------------------------------------- /4_Collections/Slice4Append.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | nish := []string{} //create empty string 7 | // nish[0] = "Nishkarsh" // Error because empty string is nil without any size and index - 8 | 9 | // Append a value 10 | nish = append(nish, "Nishkarsh") 11 | fmt.Println(nish) 12 | 13 | // Append multiple values 14 | nish = append(nish, "Raj", "Khare") 15 | fmt.Println(nish) 16 | 17 | // Append another slice 18 | code := []string{"Wrote", "This", "Code"} 19 | nish = append(nish, code...) //ellipse is used to append only same type slices 20 | fmt.Println(nish) 21 | } 22 | -------------------------------------------------------------------------------- /4_Collections/Slice5Len.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | slice := []string{"Nishkarsh", "Raj", "Khare"} 7 | fmt.Println(len(slice)) 8 | } 9 | -------------------------------------------------------------------------------- /4_Collections/Slice6Nil.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | // Creating a nil slice 7 | slice := []int{} 8 | fmt.Println(slice, len(slice), cap(slice)) //lenght and capacity is zero 9 | if slice == nil { 10 | fmt.Println("The slice is empty") 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /4_Collections/Slice7Range.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | sl := []int{1, 2, 4, 8, 16, 32, 64, 128, 256} 7 | 8 | // 1. range function returns index and value 9 | for index, value := range sl { 10 | fmt.Printf("2**%d = %d\n", index, value) 11 | } 12 | 13 | // 2. Skip Index with _ 14 | for _, value := range sl { 15 | fmt.Printf("%d ", value) 16 | } 17 | fmt.Println() 18 | 19 | // 3. Skip Value 20 | for i := range sl { 21 | fmt.Printf("%d ", i) 22 | } 23 | fmt.Println() 24 | 25 | // 4. break keyword - Print first 4 elements 26 | for i, v := range sl { 27 | if i == 4 { 28 | break 29 | } 30 | fmt.Printf("%d ", v) 31 | } 32 | fmt.Println() 33 | 34 | // 5. Continue keyword - Skip 4th element 35 | for i, v := range sl { 36 | if i == 3 { 37 | continue 38 | } 39 | fmt.Printf("%d ", v) 40 | } 41 | fmt.Println() 42 | 43 | } 44 | -------------------------------------------------------------------------------- /5_ControlFlow/CharFrequency.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | import "strings" 5 | 6 | func main() { 7 | nish := "Nishkarsh Raj Khare" 8 | // count number of vowels in name 9 | count := strings.Count(nish, "a") + strings.Count(nish, "A") + strings.Count(nish, "E") + strings.Count(nish, "e") + strings.Count(nish, "i") + strings.Count(nish, "I") + strings.Count(nish, "O") + strings.Count(nish, "o") + strings.Count(nish, "u") + strings.Count(nish, "U") 10 | fmt.Println(count) 11 | } 12 | -------------------------------------------------------------------------------- /5_ControlFlow/Exercise1.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | import "strconv" 5 | import "encoding/json" 6 | import "strings" 7 | 8 | var ( 9 | coins = 50 10 | users = []string{ 11 | "Matthew", "Sarah", "Augustus", "Heidi", "Emilie", 12 | "Peter", "Giana", "Adriano", "Aaron", "Elizabeth", 13 | } 14 | distribution = make(map[string]int, len(users)) 15 | a, e, i, o, u, sum int 16 | ) 17 | 18 | func GetResult([]string) string { 19 | //insert code here 20 | // access each name of users array - global 21 | for _, name := range users { 22 | // sum the coins according to occurence of each vowel and assign to map | check for >10 23 | a, e, i, o, u, sum = 0, 0, 0, 0, 0, 0 24 | a = strings.Count(name, "a") + strings.Count(name, "A") 25 | e = strings.Count(name, "e") + strings.Count(name, "E") 26 | i = strings.Count(name, "i") + strings.Count(name, "I") 27 | o = strings.Count(name, "o") + strings.Count(name, "O") 28 | u = strings.Count(name, "u") + strings.Count(name, "U") 29 | sum = a + e + 2*i + 3*o + 4*u 30 | if sum > 10 { 31 | sum = 10 32 | } 33 | distribution[name] = sum 34 | } 35 | 36 | fmt.Println(distribution) 37 | fmt.Println("Coins left:", coins) 38 | return strconv.Itoa(distribution["Matthew"]) + " " + strconv.Itoa(distribution["Sarah"]) + " " + strconv.Itoa(distribution["Augustus"]) + " " + strconv.Itoa(distribution["Heidi"]) + " " + strconv.Itoa(distribution["Emilie"]) + " " + strconv.Itoa(distribution["Peter"]) + " " + strconv.Itoa(distribution["Giana"]) + " " + strconv.Itoa(distribution["Adriano"]) + " " + strconv.Itoa(distribution["Aaron"]) + " " + strconv.Itoa(distribution["Elizabeth"]) 39 | } 40 | -------------------------------------------------------------------------------- /5_ControlFlow/For.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | func main() { 9 | // 1. For loop basic 10 | for i := 1; i <= 10; i++ { 11 | fmt.Printf("%d ", i) 12 | } 13 | 14 | // 2. For loop without pre and post statements 15 | i := 1 // last i is out of scope - redeclaration 16 | for i <= 10 { 17 | fmt.Printf("%d ", i) 18 | i += 1 19 | } 20 | 21 | // 3. For loop as while loop 22 | i = 1 23 | for i <= 10 { 24 | fmt.Printf("%d ", i) 25 | i += 1 26 | } 27 | 28 | // 4. Infinite loop - print Hello World for 0.0001 seconds 29 | start := time.Now() 30 | for { 31 | fmt.Println("Hello, World!") 32 | if time.Since(start).Seconds() > 0.0001 { 33 | break 34 | } 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /5_ControlFlow/If.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | n := 5 7 | 8 | // Single condition 9 | if n == 5 { 10 | fmt.Println("First Check!") 11 | } 12 | 13 | // Multiple conditions 14 | if i := 4; i%2 == 1 { 15 | fmt.Println("Second Check!") 16 | } 17 | 18 | // If else statement 19 | 20 | if false { 21 | //wont execute 22 | } else { 23 | fmt.Println("Third Check!") 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /5_ControlFlow/InfiniteForOSTime.go: -------------------------------------------------------------------------------- 1 | // Just for fun - Loading Screen Emulation for 0.001 seconds and then pause 2 seconds and refresh the Linux console 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | "os" 7 | "os/exec" 8 | "time" 9 | ) 10 | 11 | func main() { 12 | 13 | // loading screen 14 | start := time.Now() 15 | for time.Since(start).Seconds() <= 0.001 { //for acts like while 16 | fmt.Println("Loading... Please Wait!") 17 | } 18 | 19 | // Sleep for 2 seconds 20 | time.Sleep(2 * time.Second) 21 | 22 | // Clear Screen 23 | cmd := exec.Command("clear") // command to console 24 | cmd.Stdout = os.Stdout // command sent to console 25 | cmd.Run() // execute command 26 | } 27 | -------------------------------------------------------------------------------- /5_ControlFlow/Switch.go: -------------------------------------------------------------------------------- 1 | // only same type for all cases 2 | // 1. multiple values in same case can be there 3 | // no runs for all successive cases if matched unlike C 4 | // 2. To do above, fallthrough keyword can be used 5 | // 3. To break fallthrough, break can be used 6 | 7 | package main 8 | 9 | import "fmt" 10 | 11 | func main() { 12 | num := 5 13 | 14 | // 1. Multiple values 15 | switch num { 16 | case 0, 1, 2, 3: 17 | fmt.Println("Fail") 18 | case 4, 5, 6: 19 | fmt.Println("Average") 20 | case 7, 8, 9: 21 | fmt.Println("Good") 22 | case 10: 23 | fmt.Println("Perfect") 24 | default: 25 | fmt.Println("No match found") 26 | } 27 | 28 | // 2. Fall through 29 | switch num { 30 | case 0, 1, 2, 3: 31 | fmt.Println("Fail") 32 | fallthrough 33 | case 4, 5, 6: 34 | fmt.Println("Average") 35 | fallthrough 36 | case 7, 8, 9: 37 | fmt.Println("Good") 38 | fallthrough 39 | case 10: 40 | fmt.Println("Perfect") 41 | fallthrough 42 | default: 43 | fmt.Println("No match found") 44 | } 45 | 46 | // 3. Break 47 | switch num { 48 | case 0, 1, 2, 3: 49 | fmt.Println("Fail") 50 | fallthrough 51 | case 4, 5, 6: 52 | fmt.Println("Average") 53 | fallthrough 54 | case 7, 8, 9: 55 | fmt.Println("Good") 56 | fallthrough 57 | case 10: 58 | fmt.Println("Perfect") 59 | break // dont print Default 60 | default: 61 | fmt.Println("No match found") 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /5_ControlFlow/WordBreak.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | import "strings" 5 | 6 | func main() { 7 | nish := "Nishkarsh Raj Khare" 8 | array := strings.Fields(nish) 9 | fmt.Println(array) 10 | } 11 | -------------------------------------------------------------------------------- /6_Methods/CodeOrganization.go: -------------------------------------------------------------------------------- 1 | // 1. Packages and import 2 | package main 3 | 4 | import "fmt" 5 | 6 | // 2. Global constants 7 | const ( 8 | fact = "Sun rises in the East" 9 | ) 10 | 11 | // 3. Global variables 12 | var ( 13 | Exported = "Hello, World!" 14 | nonExported = "Bye!" 15 | ) 16 | 17 | // 4. Type Declarations 18 | type Person struct { 19 | fName, lName string 20 | } 21 | 22 | type Student struct { 23 | sap int 24 | roll string 25 | p Person 26 | } 27 | 28 | // 5. Functions - New User with function call 29 | func Constructor(f, l string) Student { 30 | obj := Student{sap: 500000000, roll: "R1XXXXXXXX", p: Person{fName: f, lName: l}} 31 | return obj 32 | } 33 | 34 | // 6. Methods 35 | func (p Person) Greetings() string { 36 | return fmt.Sprintf("Hello %s\n", p.fName) 37 | } 38 | 39 | // 7. Driver Code 40 | func main() { 41 | 42 | // Create a person object 43 | person1 := Person{fName: "Karan", lName: "Nautiyal"} 44 | fmt.Println(person1) 45 | fmt.Println(person1.Greetings()) 46 | 47 | // Create a student object 48 | student1 := Student{sap: 500060720, roll: "R171217041", p: Person{fName: "Nishkarsh", lName: "Raj"}} 49 | fmt.Println(student1) 50 | // Composition allows child struct to call method of base struct 51 | fmt.Println(student1.p.Greetings()) 52 | 53 | // Create student with Create function 54 | student2 := Constructor("Megha", "Rawat") 55 | fmt.Println(student2) 56 | } 57 | -------------------------------------------------------------------------------- /6_Methods/CodeOrganization2.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // list of packages to import 4 | import ( 5 | "fmt" 6 | ) 7 | 8 | // list of constants 9 | const ( 10 | ConstExample = "const before vars" 11 | ) 12 | 13 | // list of variables 14 | var ( 15 | ExportedVar = 42 16 | nonExportedVar = "so say we all" 17 | ) 18 | 19 | // Main type(s) for the file, 20 | // try to keep the lowest amount of structs per file when possible. 21 | type User struct { 22 | FirstName, LastName string 23 | Location *UserLocation 24 | } 25 | 26 | type UserLocation struct { 27 | City string 28 | Country string 29 | } 30 | 31 | // List of functions 32 | func NewUser(firstName, lastName string) *User { 33 | return &User{FirstName: firstName, 34 | LastName: lastName, 35 | Location: &UserLocation{ 36 | City: "Santa Monica", 37 | Country: "USA", 38 | }, 39 | } 40 | } 41 | 42 | // List of methods 43 | func (u *User) Greeting() string { 44 | return fmt.Sprintf("Dear %s %s", u.FirstName, u.LastName) 45 | } 46 | 47 | func main() { 48 | us := User{FirstName: "Matt", 49 | LastName: "Damon", 50 | Location: &UserLocation{ 51 | City: "Santa Monica", 52 | Country: "USA"}} 53 | fmt.Println(us.Greeting()) 54 | } 55 | -------------------------------------------------------------------------------- /6_Methods/MethodReceiverPointers.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | type User struct { 8 | FirstName, LastName string 9 | } 10 | 11 | func (u *User) Greeting() string { //pointers 12 | return fmt.Sprintf("Dear %s %s", u.FirstName, u.LastName) 13 | } 14 | 15 | func main() { 16 | u := &User{"Matt", "Aimonetti"} // Pointer input needs pointer object 17 | fmt.Println(u.Greeting()) 18 | } 19 | -------------------------------------------------------------------------------- /6_Methods/MethodStruct.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type student struct { 6 | name string 7 | sap int 8 | } 9 | 10 | // method to string 11 | func (s student) Register() string { 12 | return fmt.Sprintf("%s is registered with %d SAP ID\n", s.name, s.sap) 13 | } 14 | 15 | func main() { 16 | stu := student{"Nishkarsh", 500060720} 17 | fmt.Println(stu.Register()) 18 | } 19 | -------------------------------------------------------------------------------- /6_Methods/TypeAlias.go: -------------------------------------------------------------------------------- 1 | // Alias is used to define functions on inbuilt types 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | "strings" 8 | ) 9 | 10 | // String type 11 | type nish string 12 | 13 | // User defined alias functions always called as type("argument").function() 14 | func (s nish) UpUp() string { 15 | return strings.ToUpper(string(s)) //convert user defined type to string 16 | } 17 | 18 | func main() { 19 | 20 | // hi := "Hello" // To use Imported methods - have to export variable - capitalize them 21 | Hi := "Hello" 22 | fmt.Println(strings.ToUpper(Hi)) 23 | fmt.Println(nish("World!").UpUp()) 24 | } 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Storms In Brewing 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## The Golang Guide 2 | 3 | ![Cover Image](docs/cover.gif) 4 | 5 | ### Running Golang on *Nix 6 | 7 | #### Installation 8 | 9 | ``` 10 | $ apt install -y golang-go 11 | ``` 12 | 13 | #### Check version 14 | 15 | ``` 16 | $ go version 17 | ``` 18 | 19 | #### Standardize File Format 20 | 21 | ``` 22 | $ go fmt [filename] 23 | ``` 24 | 25 | #### Create a Platform Independent Build 26 | 27 | ``` 28 | $ go build [filename] 29 | $ ./[filename] 30 | ``` 31 | 32 | #### Execute a golang program 33 | 34 | ``` 35 | $ go run [filename] 36 | ``` 37 | 38 | ### License 39 | 40 | This project follows the [MIT License](LICENSE) - :copyright: StormsinBrewing :tm: - 2021 41 | -------------------------------------------------------------------------------- /docs/cover.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stormsinbrewing/The-Golang-Guide/9cb2cfa36a2a41706f3e6d612c560e8ec5c14192/docs/cover.gif --------------------------------------------------------------------------------