Golang自定义包导入

# 文件Tree
project
-/bin
-/pkg
-/src
    -main.go
    -/test
        -test1.go
        -test2.go

main.go

package main

import (
    "fmt"
    "./test"
)
    

func main() {
        fmt.Print("test1\n")
        test.Ojbk1()
        fmt.Print("test2\n")
        test.Ojbk2("okokok")  
}

test/test1.go

package test

import "fmt"

func Ojbk1() {
    fmt.Println("This is test1 , done ")
}

test/test2.go

package test

import "fmt"

func Ojbk2(info) {
    fmt.Println(info)
}

1.import语句使用的是文件夹的名称

  • 上面的import后面的参数对应的就是文件夹test
  • 导入方式:import(./test)

2.文件夹的名称和package的名称不一定相同

上面的例子中,文件夹是test,package名称是test(也可以写别的名称)。

3.调用自定义包使用package名称.函数名的方式

例如上面使用的test.Ojkb1()

4.自定义包的调用和文件名没有关系

例如上面的test1.go文件,如果改成test_xxxx.go,程序也能正常编译。编译系统会自动查找test文件夹下的所有文件,在其中寻找package test,然后选择Ojbk1函数。

参考链接:

https://my.oschina.net/zlLeaf/blog/174404
https://studygolang.com/articles/12842?fr=sidebar

猜你喜欢

转载自www.cnblogs.com/kumata/p/10230924.html