{"id":4269,"date":"2020-11-01T20:23:33","date_gmt":"2020-11-01T14:53:33","guid":{"rendered":"https:\/\/golangbyexamples.com\/?p=4269"},"modified":"2020-11-01T20:23:40","modified_gmt":"2020-11-01T14:53:40","slug":"import-local-module-golang","status":"publish","type":"post","link":"https:\/\/golangbyexamples.com\/import-local-module-golang\/","title":{"rendered":"Importing package from different module locally in Go (Golang)"},"content":{"rendered":"\n
There are cases when we want to import a module which is present locally. Let’s understand how we can import such module. But first, we have to create a module that can be used by others and then import it into the other module. For that let’s create two modules<\/p>\n\n\n\n
school<\/strong> module will be calling code of the sample.com\/math<\/strong> module<\/p>\n\n\n\n Let’s first create the sample.com\/math<\/strong> module which will be used by school<\/strong> module<\/p>\n\n\n\n Now <\/strong>let’s create the school module<\/p>\n\n\n\n Now do a go run<\/p>\n\n\n\n It is able to call the Add function of the sample.com<\/a>\/math\u00a0 <\/strong>module and correctly gives the output as 6.<\/p>\n\n\n\ngo mod init sample.com\/math<\/code><\/pre>\n\n\n\n
package math\n\nfunc Add(a, b int) int {\n\treturn a + b\n}<\/code><\/pre>\n\n\n\n
go mod init school<\/code><\/pre>\n\n\n\n
module school\n\ngo 1.14\n\nreplace sample.com\/math => ..\/math<\/code><\/pre>\n\n\n\n
package main\n\nimport (\n\t\"fmt\"\n\t\"sample.com\/math\"\n)\n\nfunc main() {\n\tfmt.Println(math.Add(2, 4))\n}<\/code><\/pre>\n\n\n\n
go run school.go<\/code><\/pre>\n\n\n\n