歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Golang 小技巧分享

Golang 小技巧分享

日期:2017/3/1 9:11:10   编辑:Linux編程

1.前言

Golang 開發過程中的一些小技巧在這裡記錄下。

2.內容

1)包的引用

經常看到Golang代碼中出現 _ "controller/home" 類似這種的引用,這裡的下劃線有什麼作用呢? 其實默認每個文件都有一個init函數,加下劃線表示引入這個包,僅執行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.")
}運行結果如下:


C:/Go\bin\go.exe run D:/GoProject/src/main.go
init func in golang.
this is main function
this is local func of init.
I can be called outside.

Process finished with exit code 0如果我們使用 _ "hello/golang",運行則報錯如下:


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

其實對於go來說,根本看不到這個函數,如果使用intellij,IDE 不允許用下劃線的同時調用這個包裡面的函數。

2)函數不定參數

通常我們認為函數的參數個數是一定的,但是在Golang裡面,函數的參數可以是不定的。由於函數的返回值可以是多個,這也使得Golang非常靈活,表達能力特別強。


package main

import (
"fmt"
)

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

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

運行結果:

hello
golang3)

接口使用


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接口。

Copyright © Linux教程網 All Rights Reserved