Golang 小技巧

来源:互联网 发布:眉笔推荐 知乎 编辑:程序博客网 时间:2024/05/20 20:22

1.前言

Golang 开发过程中的一些小技巧在这里记录下。

2.内容

1)包的引用

经常看到Golang代码中出现 _ "controller/home" 类似这种的引用,这里的下划线有什么作用呢? 其实默认每个文件都有一个init函数,加下划线表示引入这个包,仅执行init函数,

别的函数在外边是不能调用的。注意这里的几个说法:仅仅执行init函数,也就是说我们可以再init函数里面做一些操作,比如初始化一些东西。别的函数在外部是不能被调用的,

强行调用会报错。这里的示例代码结构如下:

- main.go

-- hello

----golang

------ init.go

main.go 

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

package worldimport (    "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.goinit func in golang.this is main functionthis 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 mainimport ("fmt")func MyPrint(str ...string) {for _, s := range str {fmt.Println(s)}}func main() {MyPrint("hello", "golang")}
运行结果:
hellogolang
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接口。







0 0