加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang 小技巧

发布时间:2020-12-16 18:30:16 所属栏目:大数据 来源:网络整理
导读:1.前言 Golang 开发过程中的一些小技巧在这里记录下。 2.内容 1)包的引用 经常看到Golang代码中出现 _ "controller/home" 类似这种的引用,这里的下划线有什么作用呢? 其实默认每个文件都有一个init函数,加下划线表示引入这个包,仅执行init函数, 别的函

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读