1, create new project "test8_method"
$ cd ~/project
$ mkdir test8_method
$ cd test8_method
$ touch method.go
2,add following lines in “method.go”
package main
import (
"fmt"
)
type Book struct {
author string
publish uint64
}
type Bus struct {
startStation string
terminalStation string
}
type Number int
func (book Book) printInfo() {
fmt.Println("Book", book)
}
func (bus Bus) printInfo() {
fmt.Println("Bus:", bus)
}
func (bus *Bus) printInfoP() {
fmt.Println("BusP:", bus)
}
func (bus Bus) changeInfo() {
bus.startStation = "Unseo" // this line will not change bus.startStation when return
}
func (bus *Bus) changeInfoP() {
bus.startStation = "Unseo" // this line will change bus.startStation when return
}
func (n Number) selfAdd() (r Number) {
r = n + 1
return
}
func main() {
// TEST 1, method
var _book = Book{"Henry David Thoreau", 1854}
var _bus = Bus{"Souel", "Incheon"}
var _n = Number(3)
_book.printInfo()
_bus.printInfo()
fmt.Println(_n.selfAdd())
// TEST 2, method and pointer
var _busP = &Bus{"Incheon", "Souel"}
fmt.Println("_bus:", _bus)
fmt.Println("_busP:", _busP)
_bus.printInfo()
_busP.printInfo()
_bus.printInfoP()
_busP.printInfoP()
_bus.changeInfo()
_busP.changeInfo()
fmt.Println("_bus:", _bus)
fmt.Println("_busP:", _busP)
_bus.changeInfoP()
_busP.changeInfoP()
fmt.Println("_bus:", _bus)
fmt.Println("_busP:", _busP)
}
3, run “method.go”
go run method.go
you should get result like this:
Book {Henry David Thoreau 1854}
Bus: {Souel Incheon}
4
_bus: {Souel Incheon}
_busP: &{Incheon Souel}
Bus: {Souel Incheon}
Bus: {Incheon Souel}
BusP: &{Souel Incheon}
BusP: &{Incheon Souel}
_bus: {Souel Incheon}
_busP: &{Incheon Souel}
_bus: {Unseo Incheon}
_busP: &{Unseo Souel}