Its just the basics, where I have summed up the syntaxes for writing golang
You atleast should know some programming basics to understand this. It is for my journal, as I would approach myself to learn golang. I have worked in javascript and trying out golang for my learning. And this is how I learn basics before building.
Basic golang main() that prints Hello World
package mainimport ( "fmt")func main() { fmt.Println("Hello World")}
Variable declarations
package mainimport ( "fmt" "strings")func main() { likes, comments := 1000, 30 fmt.Println(likes, comments) name, age := "Sangram", 30 fmt.Println(strings.ToUpper(name), age) const pName = "Sangram" fmt.Println(pName)}
- Except pName, all other variables are mutable as pName, is a constant
- := –> this operator is only applicable inside a function, not outside of it
If Condition
package mainimport ( "fmt")func main() { noOfItems := 15 pricePerItem := 20 if total := noOfItems * pricePerItem; total >= 100 { fmt.Println("Free Shipping") } else { fmt.Println("Apply Shipping Cost") }}
NOTE: total is local to the if condition, as it is not accessible to outside the if-else block
For Loop
package mainimport ( "fmt")func main() { for i := 0; i < 5; i++ { fmt.Println(i) }}
Arrays/Slices
package mainimport ( "fmt")func main() { var arr [3]int arr[0] = 1 arr[1] = 2 arr[2] = 3 fmt.Println(arr) arr2 := [3]int{5, 6, 7} fmt.Println(arr2) slice1 := []int{8, 9} fmt.Println(slice1) slice1[1] = 10 fmt.Println(slice1) // Append to a slice var slice2 []int slice2 = append(slice2, 11) slice2 = append(slice2, 12, 13) fmt.Println(slice2) // Use make() to create a slice slice3 := make([]int, 0, 5) fmt.Println(slice3, len(slice3), cap(slice3)) slice4 := []int{14, 15} slice5 := []int{16, 17} slice4 = append(slice4, slice5...) // Merge 2 slices fmt.Println(slice4) sum := 0 nums := []int{18, 19, 20} for i, v := range nums { fmt.Println("index", i, "num", v) sum += v } fmt.Println(sum)}
- Arrays are fixed in length, we cannot extend it
- Slices are variable in length and increases in double
- append() is used to add elements and merge slices
- make() can be used to create slice
- slice5…: spread operator to be used to spread the slice so that all the elements of slice5 can be added to slice4
- range: it can be used to loop through slices
Maps/Objects
package mainimport ( "fmt")func main() { ages := map[string]int{ "sangram": 30, } fmt.Println(ages) fmt.Println(ages["sangram"]) fmt.Println(ages["sangram2"]) // empty key value in map() var mapData map[string]int mapData = make(map[string]int) mapData["sangram"] = 30 fmt.Println(mapData) delete(mapData, "sangram") delete(mapData, "sangram2") // no error in map delete fmt.Println(mapData) mapData2 := make(map[string]int) mapData2["rakesh"] = 33 if _, ok := mapData2["rakesh2"]; ok { fmt.Println("We have key value pair") } else { fmt.Println("We do not have key value pair") } mapData3 := map[string]int{ "biscuit": 10, "mixture": 100, } for item, price := range mapData3 { fmt.Println("item", item) fmt.Println("price", price) }}
- while deleting a value from the map, if we do not have that then go wont throw an error
- range can also be used to loop thru map
- to check for key in the map, we need to explicitly check it, may be a separate function needed to be made for that
Functions
package mainimport ( "fmt" "strconv")func main() { // func inside func add := func(a int, b int) int { return a + b } sum2 := add(1, 2) fmt.Println(sum2) // define and invoke add3 := func(a int, b int) int { return a + b }(1, 2) fmt.Println(add3) sum3 := add2(3, 4) fmt.Println(sum3) sumNProduct := func(a, b int) (int, int) { return a + b, a * b } sum4, prod := sumNProduct(5, 6) fmt.Println(sum4, prod) x, y := namedReturns(3) fmt.Println(x, y) // variadic function sumOfCubes := func(nums ...int) int { sum := 0 for _, num := range nums { sum += num * num * num } return sum } result2 := sumOfCubes(slice4...) fmt.Println(result2) parseLevel := func(s string) (int, error) { n, err := strconv.Atoi(s) if err != nil { return 0, fmt.Errorf("level must be a number") } if n < 1 || n > 5 { return 0, fmt.Errorf("level must be between 1 and 5") } return n, nil } level, err := parseLevel("30") if err != nil { fmt.Println("Error while parsing level") } else { fmt.Println(level) }}func add2(a, b int) int { return a + b}// func with named returnsfunc namedReturns(a int) (sqr int, cube int) { sqr = a * a cube = a * a * a return}
Defer
Its like cleanup before function ends. Something like return () => {} in useEffect, for React devs
package mainimport ( "fmt" "errors")func main() { // Learn Defer learnDefer := func(succes bool) error { fmt.Println("start working with resource") defer fmt.Println("will always get called before the function ends... cleaning up resources") if !succes { return errors.New("Error occured") } fmt.Println("resources work finished") return nil } if err := learnDefer(true); err == nil { fmt.Println("No errors") } if err := learnDefer(false); err != nil { fmt.Println("Errors occured") }}
Pointers
package mainimport ( "fmt")func main() { score := 20 fmt.Println("score value b4 changing:", score) changeScore := func(score *int) { *score += 5 } changeScore(&score) fmt.Println("score avlue after changing w/pointer:", score) changeScore2 := func(score int) { score += 5 } changeScore2(score) fmt.Println("score value after changing w/o pointer:", score) user := User{FirstName: "Sangram", MiddleName: "", LastName: "Mohanty", Age: 30} fmt.Println("b4 Age normal receiver:", user.Age) // struct reciever normal fmt.Println(user.FullName()) fmt.Println("after Age normal receiver:", user.Age) // struct reciever pointer fmt.Println(user.HappyBirthday()) fmt.Println("after Age pointer receiver:", user.Age)}type User struct { FirstName string MiddleName string LastName string Age int}func (u User) FullName() string { u.Age++ return fmt.Sprintf("Hi, my name is %s", u.FirstName+" "+u.MiddleName+" "+u.LastName)}func (u *User) HappyBirthday() string { u.Age++ return fmt.Sprintf("Hi, my name is %s", u.FirstName+" "+u.MiddleName+" "+u.LastName)}
- We can add functionality/methods to struct
- We can change the value of the pointers by passing its reference
Leave a comment