Golang Local Module with OOP
Create location of your go code
1~$ mkdir /mnt/c/learning/go
Get the suggested golang init script
It is in separate post in my quicktasks
and don't forget to make it executable. For this quicktask, I assume you named it init.sh as well.
Create and go to project directory
1~$ mkdir local_module_example
2~$ cd local_module_example
Initialize Go environment
1../init.sh
Create module location directory
1~$ mkdir -p example.local/person
Create the module
This is module person
1~$ cat > example.local/person/person.go << MODULE_BODY
2package person
3
4type person struct {
5 firstName string
6 lastName string
7 age int
8}
9
10func New(firstName string, lastName string, age int) person {
11 p := person{
12 firstName: firstName,
13 lastName: lastName,
14 age: age,
15 }
16
17 return p
18}
19
20func (p person) ShowFirstName() string {
21 return p.firstName
22}
23
24func (p person) ShowLastName() string {
25 return p.lastName
26}
27
28func (p person) ShowAge() int {
29 return p.age
30}
31MODULE_BODY
Mark it as a module
1~$ cd example.local/person
2~$ go mod init person
In main
1~$ cd ../../
2~$ mkdir src
3~$ cat > src/main.go << MAIN_BODY
4package main
5
6import (
7 "example.local/person"
8 "fmt"
9)
10
11func main() {
12 man := person.New(
13 "George",
14 "Washington",
15 290,
16 )
17
18 fmt.Println("First Name:", man.ShowFirstName())
19 fmt.Println("Last Name: ", man.ShowLastName())
20 fmt.Println("Age: ", man.ShowAge())
21}
22MAIN_BODY
Point person module to local
~$ cd src ~$ go mod init main ~$ go mod edit -replace example.local/person=../example.local/person ~$ go mod tidy
Run it
1~$ go mod run main
2First Name: George
3Last Name: Washington
4Age: 290