{"id":4275,"date":"2020-11-02T22:08:04","date_gmt":"2020-11-02T16:38:04","guid":{"rendered":"https:\/\/golangbyexamples.com\/?p=4275"},"modified":"2020-11-02T22:08:11","modified_gmt":"2020-11-02T16:38:11","slug":"importing-package-same-module-go","status":"publish","type":"post","link":"https:\/\/golangbyexamples.com\/importing-package-same-module-go\/","title":{"rendered":"Importing package within the same module in Go (Golang)"},"content":{"rendered":"\n
Any package within the same module can be imported using the import path of module + directory containing that package. To illustrate lets create a module<\/p>\n\n\n\n
go mod init learn<\/code><\/pre>\n\n\n\n- Now create main.go (Having main package and main function)<\/li><\/ul>\n\n\n\n
- And math\/math.go – math package<\/li><\/ul>\n\n\n\n
main.go<\/strong><\/p>\n\n\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"learn\/math\"\n)\n\nfunc main() {\n\tfmt.Println(math.Add(1, 2))\n}<\/code><\/pre>\n\n\n\nmath\/math.go<\/strong><\/p>\n\n\n\npackage math\n\nfunc Add(a, b int) int {\n return a + b\n}<\/code><\/pre>\n\n\n\nSee how we have imported the math package in the main.go file<\/p>\n\n\n\n
\"learn\/math\"<\/code><\/pre>\n\n\n\nHere the import path is import path of module which is learn<\/strong> +\u00a0 directory containing the package which is math. <\/strong>Hence “learn\/math” . Packages in nested directory can also be imported in the same way. The way it works is that since the prefix is the module import path, hence go will know that you are trying to import from the same module. So it will directly refer it instead of downloading it.<\/p>\n","protected":false},"excerpt":{"rendered":"Any package within the same module can be imported using the import path of module + directory containing that package. To illustrate lets create a module Make a learn directory Create a…<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","footnotes":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false},"categories":[1],"tags":[3,4],"class_list":["post-4275","post","type-post","status-publish","format-standard","hentry","category-tech","tag-go","tag-golang"],"yoast_head":"\n
Importing package within the same module in Go (Golang) - Welcome To Golang By Example<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n