For reusable purpose, package is a good start to manage your Go codes because we can import and use it to our program.
Lets create a simple main file to begin with
package main import "fmt" func main() { fmt.Println("hello world!") }
It's a simple hello world program that printed out hello world string when we run go run main.go .
Now lets initiate a package with creating the module first. Commonly it's using a git repository even we have no plan to push it to any repository out there. In this example I will use my own Github repository and use mygopackageas package name.
git mod init github.com/didikz/mygopackage
Then create a subdirectory, for example I use models and create a user.go inside of it. The structure should be looks like this
Inside user.go I would simple create a struct and a receiver that could be imported later in the main.go . I also set package name following the current directory name as models
package models type User struct { Id int FirstName string LastName string Address string } func (user *User) GetName() string { return user.FirstName " " user.LastName }
Get back to main.go and now we can try to import the package and use the defined struct. Use the module name initiated before along with the package name.
import "github.com/didikz/mygopackage/models"
Now to use the user model from the package we can write like this
var user models.User user.Id = 1 user.FirstName = "Didik" user.LastName = "Tri Susanto" user.Address = "Malang" // or alternatively user := models.User{Id: 1, FirstName: "Didik", LastName: "Tri Susanto", Address: "Malang"} fmt.Println(user.GetName())
All set. Next, If we run go run main.go then it should printed out Didik Tri Susanto
Easy right?
The final main.go file now should be like this
package main import ( "fmt" "github.com/didikz/mygopackage/models" ) func main() { user := models.User{Id: 1, FirstName: "Didik", LastName: "Tri Susanto", Address: "Malang"} fmt.Println(user.GetName()) }
That's it and happy coding!
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3