Skip to content

Instantly share code, notes, and snippets.

@yashprit
Last active August 29, 2015 14:17
Show Gist options
  • Save yashprit/058ab708bfa1b7762d6a to your computer and use it in GitHub Desktop.
Save yashprit/058ab708bfa1b7762d6a to your computer and use it in GitHub Desktop.
Hello Golang
//playground runner https://play.golang.org/p/FkoEDVPB1n
package main
import (
"fmt"
)
func main() {
z := iKnowNamedReturs()
fmt.Println(z)
letsLearnControlFlow()
}
func iKnowNamedReturs() (z int) {
z = 3 + 2
return
}
func letsLearnControlFlow() {
//see syntax, it require brackets
if 3 > 2 {
fmt.Println("2 is smaller than 3")
}
if !false {
fmt.Println("I can change flag")
}
x := 42.0
//see there are no parens
switch x {
case 42:
fmt.Println("number is 42")
break
case 43.0:
fmt.Println("number is float")
break
}
//no parens either
for x := 0; x < 3; x++ {
fmt.Println(x)
}
//x is 42.0, here,
//variable declared in if or for are local
fmt.Println(x)
//for is only loop statement in GO, but variant forms
//function literal are closures
xBig := func() bool {
return x > 100 //can acess x here
}
fmt.Println(xBig()) //true
x = 200
fmt.Println(xBig()) //false
//function literal can be called as inline
//They invoke imediately
//return type matched with expected type of argument
fmt.Println("Addition of two number is ", func(a, b int) int {
fmt.Println(a, b)
return (a + b) * 2
}(2, 3)) //addition of two number is 10
//go to our old friend
goto love
love:
{
fmt.Println("I am from goto")
}
}
//playground link https://play.golang.org/p/kc2IVs7DRj
package main
import (
"fmt"
)
func main() {
letsLearnDefer()
}
//defer are called just before function returns
func letsLearnDefer() (ok bool) {
defer fmt.Println("defer statement executs in LIFO")
defer fmt.Println("\nthis line will be printed as first")
//defer are useally used for closing file or connectio
//it will become reposiblity of same function who has open file, he is only closing file
return true
}
//playground https://play.golang.org/p/STgNAvd7di
package main
import "fmt"
import "strconv" //string conversion
func main() {
learnErrorHandling()
}
func learnErrorHandling() {
m := map[int]string{2: "two", 3: "three"}
// ", ok" idiom used to tell if something worked or not.
if x, ok := m[1]; !ok { // ok will be false because 1 is not in the map.
fmt.Println("value not found for key")
} else {
fmt.Println(x)
}
if _, err := strconv.Atoi("non-int"); err != nil {
fmt.Println(err)
}
}
//playground link https://play.golang.org/p/_HQK1Eb6XK
package main
import (
"fmt"
)
func main() {
//when function return another function
letSeeFunctionFactories()
}
func letSeeFunctionFactories() {
fmt.Println(sentenceFactory("summer")("days", "morning"))
d := sentenceFactory("winter")
fmt.Println(d("night", "awesome"))
fmt.Println(d("evening", "wonderful"))
}
func sentenceFactory(season string) func(before, after string) string {
return func(before, after string) string {
return fmt.Sprintf("%s %s %s", before, season, after)
}
}
//single line comment
/*
Multi line comments
*/
//playground link https://play.golang.org/p/7qC3W6ZhZ-
//this will tell compiler about this being a main package
package main
//import package
import (
"fmt" //standard package in go libarary used for doing things like println
//"io/ioutil" //this can also import from any DVCS
//m "math" //import math and create m as local refence variable
)
//this funciton is starting point for your program, this is special function
func main() {
fmt.Println("my first ever program in go") //see there are no semi colons
}
//playground https://play.golang.org/p/OOW7IpgCBr
package main
import (
"fmt"
)
func main() {
learnInterface()
}
//define interface, with only one method
type Stingger interface {
String() string
}
//define struct with two variable
type pair struct {
x, y int
}
//now lets define method on pair, and have this pair implement interface method
func (p pair) String() string { //p is pair here
return fmt.Sprintf("(%d %d)", p.x, p.y)
}
func learnInterface() {
// Brace syntax is a "struct literal." It evaluates to an initialized
// struct. The := syntax declares and initializes p to this struct.
p := pair{2, 3}
fmt.Println(p.String())
var i Stingger //decalre variable for interface
i = p //valid as pair implemnet Stingger
fmt.Println(i.String())
// Functions in the fmt package call the String method to ask an object
// for a printable representation of itself.
fmt.Println(p) // Output same as above. Println calls String method.
fmt.Println(i) // Output same as above.
}
//playground link https://play.golang.org/p/YPTXWr-fco
package main
//import package
import (
"fmt"
)
func main() {
letsLearnType()
}
func letsLearnType() {
//:= take only for new variable otherwise you'll get an error like 'no new variables on left side of :='"
s := "String type" //creating string stype
s2 := "Another String" //if you're declare variable and never used it go will cause problem here.
fmt.Println(s, s2)
fmt.Println("===============")
//string can also be new line
s3 := `A "awesome string" with
new line into it` //use `` to escape any char
fmt.Println(`awesome string`, s3)
//non ASCII char go is UTF-8
g := 'Σ' // rune type, an alias for uint32, holds a unicode code point.
f := 3.14 //float64 IEEE-754 64 bit floating point number
complex := 3 + 4i //complex number
//var syntax with initlizers
var ui uint = 32 //unsigned interger, but implementation dependent size as with int.
var pi float32 = 22 / 7
n := byte('\n') //byte is alias of uint8
fmt.Println(g, f, complex, ui, pi, n) //print ASCII code of g and for pi as int of 22/7 not float32 even if its stored as float32
pi = 22. / 7
fmt.Println(pi)
//Array and Slices are two common data-struct in go, each have advantage or disadvantage
//Slices use cases are more common because of dynamic in nature
//Array have fixed size at compile time
var a4 [4]int //array with size 4, eveything
a3 := [...]int{1, 2, 3}
fmt.Println(a4, a3)
si3 := []int{1, 2, 3} //compare to array, there is no dots here called as ellipsis
si4 := make([]int, 4) //create slices of size 4 and initlize all with default of data type in this case 0
fmt.Println(si3, si4)
var d2 [][]float64 //declaration only
bs := []byte("a slice") //type conversation
fmt.Println(d2, bs)
//pointers
p, q := whatAboutMemory()
fmt.Println(p, q) //print moemory location
//I also support maps
//map are like growable associative array,
//hash or dict in some other lanaguge
m := map[string]int{"two": 2, "three": 3}
m["one"] = 1
m["one"] = 2 //can override if previosuly set
fmt.Println(m)
unused := 2
// Unused variables are an error in Go.
// The underbar lets you "use" a variable but discard its value.
_ = unused
}
func whatAboutMemory() (p, q *int) { //created two variable of type int pointers
p = new(int) //internal method to allocate memory
s := make([]int, 20) //intlized slice of 20 static memory
s[3] = 7
r := 4
return &s[3], &r
}
//play ground link https://play.golang.org/p/kcKEWHL8xE
package main
import "fmt"
func main() {
learnVeriadicParams("greet", "say", "hello")
}
//any function can accept variadic params
func learnVeriadicParams(myString ...interface{}) {
//print each params
for _, param := range myString {
fmt.Println("myParams ", param)
}
fmt.Println("my params", fmt.Sprintln(myString...))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment