Golang Local Module with OOP
Create location of your go code
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
Initialize Go environment
Create module location directory
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
go
Mark it as a module
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
go
Point person module to local
~$ cd src ~$ go mod init main ~$ go mod edit -replace example.local/person=../example.local/person ~$ go mod tidy