6/14 Golang 紀錄


Golang ¶

1. Basic Data Type ¶

int int8 int16 int32 int64
uint uint8 uint16 uint32 uint64

alias for uint8

alias for int32

represents a Unicode code point

float32 float64
complex64 complex128

2. Declaration ¶

// 以下兩式相同意思
var i int = 100
i := 100

//Declare constant
const Truth = ture;
const world = "世界"
const Pi = 3.1415926

3. Loop ¶

//Type 1
for i = 0; i < 10; i++ {
    // do something...
}

// Type 2
sum := 1;
for ; sum < 1000; {
    sum += sum
}

// Type 3
// ary is an array
for i, item := range ary {
    // i is index
    // item is value
}
sum := 0;
for sum < 1000 {
    sum += sum;
}

4. If ¶

if can start with a short statement to execute before condition

if i := math.Pow(2,2); i < 100 {
    // do sth...
}

5. Defer ¶

defer fmt.Println("world")
defer fmt.Println("world2")

fmt.Println("hello")
fmt.Println("hello")
fmt.Println("hello")

// result
hello
hello
hello
world2
world

6. Pointer ¶

The *T is a pointer to a T Value. Its zero type is nil

i := 100
var p *int = &i //Declaration
p := &i // Short declaration

7. Structrue ¶

package main

import "fmt"

type Vertex struct {
    X int
    Y int
}

func main() {
    fmt.Println(Vertex{1, 2})

    v := Vertex{1, 2}
    v.X = 4
    fmt.Println(v.X)
}

// result
{1 2}
4
package main

import "fmt"

type Vertex struct {
    X, Y int
}

var (
    v1 = Vertex{1, 2}
    v2 = Vertex{X: 1} // Y: 0 is implicit
    v3 = Vertex{}     // X: 0 Y: 0
    p = &Vertex{1, 2}
)

func main(){
    fmt.Println(v1, v2, v3, p)
}

// Result
{1 2} {1 0} {0 0} &{1 2}
s := []struct{
    i int
    b bool
}{
    {1, true},
    {2, false},
    {3, true},
    {4, true},
}

8. Array ¶

The type [n]T is an array of n values of type T

var a [2]string
a[0] = "hello"
a[1] = "world!"
fmt.Println(a[0], a[1])
fmt.Println(a)

primes := [6]int{2, 3, 5, 7, 11, 13}
fmt.Println(primes)

// Result
Hello World
[Hello World]
[2 3 5 7 11 13]

又開始懷念過去了,不過再懷念還是過去了

放假太長也是一種煩腦啊,好久不見的長假