GO Basic Command Line
Table of Content:
Installation and Setup
- Create
go.mod
file to your project
- Create go file and
main
package
- Import format
Warning: \ The GO is separate end of line with
;
and fix the{}
syntax.
- Test run main package
Declare in GO
var
is mutable and const
is immutable
- Short declaration
Note: \ All variable in GO have default value, in GO it call zero value.
Note: \ When to use short declaration
If Statement
point := 50
if point >= 50 && point <= 100 {
println("Pass")
} else if point >= 20 {
println("Not Pass")
}
For Loop
Note: \ If you do not want to use index in for-each statement, you can use
While Loop
Array
// array of int with size 3
var x [3]int = [3]int{1, 2, 3}
x := [3]int{1, 2, 3}
x := [...]int{1, 2, 3, 4}
// Create slice array
x := []int{1, 2, 3}
x = append(x, 4)
Map
var countries map[string]string
countries := map[string]string{}
countries["th"] = "Thailane"
country, ok := countries["jp"]
if !ok {
println("No value")
return
}
Function
The scope of function is in package
func main() {
c, _ := add(10, 20)
println(c)
}
func add(a, b int) (int, string) {
return a + b, "Hello"
}
func sum(a ...int) int {
s := 0
for _, v := range a {
s += v
}
return s
}
s := sum(1, 2, 3, 4, 5)
println(s)
High-order Function
func cal(f func(int,int)int) {
sumn := f(50, 10)
println(sum)
}
cal(func(a, b int) int {
return a + b
})
Package
Warning: \ In GO, if you want to export anything from another package, you should use pascal case like,
func Sum()
orvar Name =
Pointer
Note: \ If you want to use value of pointer
y
, you can useprintln(*y)
.
Struct
Struct is a class without method in GO. Attribute in GO say with behavior.
type Person struct {
Name string
Age int
}
func main() {
x := Person{"Tom", 18}
y := Person{Name: "Tom", Age: 18}
z := Person{
Name: "Tom",
Age: 18,
}
println(x.Name)
println(y.Age)
}
- Create Extension Method
- Create OOP in Struct
package customer
type Person struct {
name string
age int
}
func (p Person) GetName() string {
return p.name
}
func (p *Person) SetName() string {
p.name = name
}
func (p Person) GetAge() int {
return p.age
}
References
- https://www.youtube.com/watch?v=JbIS97exQnQ
- https://github.com/avelino/awesome-go