Hike News
Hike News

Go初識-day3-init函數、函數、常量

init函數

  • 每個原文件都可以包含一個init函數
  • 運行main函數之前會被Go的運行框架自動調用
  • 通常用於在執行main函數之前初始化

example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main

import "fmt"

var Name string = "I'm global value"

func init(){
fmt.Println("Initialize....")
fmt.Println(Name)
Name = "Name initialize..."
}

func main(){
fmt.Println("I'm main function!!")
fmt.Println(Name)
}

result

1
2
3
4
Initialize....
I'm global value
I'm main function!!
Name initialize...

tips

  • 執行順序:初始化全局變量 —> 執行init函數 —> 執行main函數
  • 要是main包中有導入其他包,會先執行其他包的init函數,最後才會執行main包中的init函數

補充

有時,用戶可能需要導入一個包,但是不需要引用這個包裡面的函數或是其他標識符,會使用空白標識符(_)給予其別名,其目的就是為了執行該包的init函數而已

1
2
3
import (
_ "fmt"
)

函數聲明

格式

1
2
3
func 函數名 (參數列表) (返回值列表){  //[1][2]
函數主體
}

[1] 即使沒有參數,()小括號也要標示
[2] 沒有返回值,則可不寫返回值;只有一個返回值則可省略()小括號

example

無參數且無返回值

1
2
3
func function_one(){

}

有參數有一返回值

1
2
3
func function_two(a int, b int)int{

}

有參數及多個返回值

1
2
3
func function_three(a,b int)(int,int){

}

註釋

Go中共使用兩種註釋

單行註釋 ( // )

1
2
3
4

func add(a,b int)int{
//add 計算兩整數和,並返回結果
}

多行註釋 ( /* */ )

1
2
3
4
5
6

func add(a,b int)int{
/*add
計算兩整數和
,並返回結果*/
}

常量

  1. 常量為const開頭修飾,代表永遠只讀,不能修改
    • 程序初始化時(編譯階段),值就決定了
  2. const只能修飾boolean,number(int,float,complex相關類型)和string

語法

1
const 常量名 [類型] = 值    //[1]

[1] 可省略類型不寫,編譯時會自動做類型推斷

example

初學者寫法

1
2
3
4
const b string = "Hello world"
const b = "Hello world"
const Pi = 3.1415926
const a = 9/3 //[1]

[1] =右邊可以是表達式,編譯時會計算完成

優雅寫法

1
2
3
4
5
const(
b = "Hello world"
Pi = 3.1415926
a = 9/3
)

專業寫法(枚舉類型)

1
2
3
4
5
const(
a = iota //[1]
b
c
)

[1] iota會將變量設為0,後續變量往後會+1,也就是說a為0,b為1,c為2

  • iota為自增值
1
2
3
4
5
6
7
const(
b = 1 << (10 * iota)
kb
mb
gb
tb
)

tips

1
const c = getvalue()

以上寫法是錯的,=右邊不能是編譯時會無法確定值的物件

practice

定義兩個常量Male=1和Female=2,獲取當前時間的秒數,如果能被Female整除則在終端顯示Female否則打印Male

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package main

import (
"fmt"
"time"
)

const (
Male = 1
Female = 2
)

func main(){
Now_second := time.Now().Unix() //[1]
if Now_second % Female == 0 {
fmt.Println("Female")
} else {
fmt.Println("Male")
}
}

[1] time.Now().Unix()獲取從1970年到現在的秒數