create Golang project with method

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}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值