Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Golang 實用小技巧:底線匯入、不定參數與介面

前言

Golang 開發過程中的一些小技巧,記錄下來備查。

1. 底線匯入的含義

常看到 _ "controller/home" 這類寫法,那個底線是什麼意思?每個 Go 檔案都有一個隱式的 init 函式,加上底線表示「只引入這個套件並執行它的 init」,套件中其他函式在外部無法呼叫,強行呼叫會編譯失敗。

也就是說,底線匯入常用於副作用:在 init 裡註冊驅動、初始化資源等。

專案結構:

- main.go
-- hello
---- golang
------ init.go
// main.go
package main

import (
    "fmt"
    "hello/golang"
)

func main() {
    fmt.Println("this is main function")
    world.Test()
}
// init.go
package world

import (
    "fmt"
)

func init() {
    fmt.Println("init func in golang.")
}

func localfun() {
    fmt.Println("this is local func of init.")
}

func Test() {
    localfun()
    fmt.Println("I can be called outside.")
}

執行結果:

init func in golang.
this is main function
this is local func of init.
I can be called outside.

若改成 _ "hello/golang",則會得到:

# command-line-arguments
.\main.go:10: undefined: world in world.Test

對 Go 而言,那個套件等於隱形,IDE 也不允許你同時用底線匯入又呼叫其中的函式。

2. 不定參數

函式參數個數可以是不定的,加上多返回值特性,Go 的表達力因此相當靈活。

package main

import (
    "fmt"
)

func MyPrint(str ...string) {
    for _, s := range str {
        fmt.Println(s)
    }
}

func main() {
    MyPrint("hello", "golang")
}

輸出:

hello
golang

3. 介面的實現是隱式的

type Print interface {
    CheckPaper(str string)
}

type HPPrint struct {
}

func (p HPPrint) CheckPaper(str string) {
    fmt.Println(str)
}

func main() {
    p := HPPrint{}
    p.CheckPaper("I am checking paper.")
}

輸出:

I am checking paper.

這裡沒有任何宣告,但我們說 HPPrint 實現了 Print 介面——只要方法集合齊備就算實現,這是 Go 與 Java 最直觀的差異之一。

Copyright © Linux教程網 All Rights Reserved