Skip to content

Instantly share code, notes, and snippets.

@zern3w
Created February 3, 2019 03:57
Show Gist options
  • Save zern3w/814be65cdbf2a8726fdbb70b900fb80c to your computer and use it in GitHub Desktop.
Save zern3w/814be65cdbf2a8726fdbb70b900fb80c to your computer and use it in GitHub Desktop.
The Basic of Golang
/*
Basic Go: Learn Go in 12 Minutes
ref: https://www.youtube.com/watch?v=C8LgvuEBraI
*/
package main
import (
"fmt"
"errors"
"math"
)
func main() {
fmt.Println("Hello, World!")
// Variable
var x int // default 0
var x int = 5
x := 5
fmt.Println(x) // result = 5
// Condition
if x > 6 {
fmt.Println("More than 6")
} else if x < 2 {
} else {
}
// Array
var a [5]int
a := [5]int{5, 4, 3, 2, 1}
a[2] = 7
fmt.Println(a) // result = [5 4 7 2 1]
// Slice
a := []int{5, 4, 3, 2, 1}
a = append(a, 13)
// Map
vertices := make(map[string]int)
vertices["triangle"] = 2
vertices["square"] = 3
vertices["dodecagon"] = 12
delete(vertices, "square")
fmt.Println(vertices) // result = map[triangle:2 square:3 dodecagon:12]
fmt.Println(vertices["triangle"]) // result = 2
// Loop
for i := 0; i < 5; i++ {
fmt.Println(i) // result = 1 2 3 4 5
}
// While loop
i := 0
for i < 5 {
fmt.Println(i) // result = 1 2 3 4 5
i++
}
// Loop over array
arr := []string{"a", "b", "c"}
for index, value := range arr {
fmt.Println("index:", index, "value:", value)
// result = index: 0 value: a
// index: 1 value: b
// index: 2 value: c
}
// Loop over map
m := make(map[string]string)
m["a"] = "alpha"
m["b"] = "beta"
for key, value := range m {
fmt.Println("key:", key, "value:", value)
// result = key: a value: alpha
// key: b value: beta
}
// Calling method
/*
func sum(x int, y int) int {
return x + y
}
*/
result := sum(2, 3)
fmt.Println(result) // result = 5
// Calling method with two return type
/*
(Require import errors, math)
func sqrt(x float64) (float64, error){
if x < 0 {
return 0, errors.New("Undefined for negative numbers")
}
return math.Sqrt(x), nil
}
*/
result, err := sqrt(16)
if err != nil {
fmt.Println(err) // result = Undefined for negative numbers
} else {
fmt.Println(result) // result = 4
}
// struct is simillar with the object of Java
/*
type person struct {
name string
age int
}
*/
p := person{name: "Jake", age: 23}
fmt.Println(p) // result = {Jake 23}
fmt.Println(p.age) // result = 23
// memory address, memory reference
/*
(this function get a copy of i, the original i wont change)
func inc(x int) {
x++
}
*/
i := 7
inc(i)
fmt.Println(i) // result = 7
/*
(this function use memery referece, the original i will change)
func inc(x *int) {
*x++
}
*/
i := 7
inc(&i)
fmt.Println(i) // result = 8
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment