Golang语言-- 小技巧

时间:2022-05-05
本文章向大家介绍Golang语言-- 小技巧,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

.前言

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:/Gobingo.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
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接口。