速戰速決 go https://github.com/webabcd/GoSample
作者 webabcd
速戰速決 go - go 面向對象: 結構體(爲結構體定義方法,使用工廠模式初始化結構體)
示例如下:
oop/struct3.go
// go 面向對象 - 結構體(爲結構體定義方法,使用工廠模式初始化結構體)
package oop
import "fmt"
func Struct3Sample() {
// 爲結構體指針添加方法
struct3_sample1()
// 爲結構體指針指向的值添加方法
struct3_sample2()
// 使用工廠模式初始化結構體
struct3_sample3()
}
func struct3_sample1() {
a := &struct31{}
// 調用結構體 struct31 的 add() 方法
a.add(0)
a.add(1)
a.add(2)
fmt.Println(a.items) // [0 1 2]
}
type struct31 struct {
items []int
}
// 爲結構體 struct31 定義一個 add() 方法,這玩意叫做接收器(receiver)
// 這裏是爲結構體指針添加方法
func (s *struct31) add(item int) {
s.items = append(s.items, item)
}
func struct3_sample2() {
a := struct32{1, 2}
b := struct32{3, 4}
// 調用結構體 struct32 的 add() 方法
c := a.add(b)
fmt.Println(c) // {4 6}
}
type struct32 struct {
x int
y int
}
// 爲結構體 struct32 定義一個 add() 方法,這玩意叫做接收器(receiver)
// 這裏是爲結構體指針指向的值添加方法
func (s struct32) add(other struct32) struct32 {
return struct32{s.x + other.x, s.y + other.y}
}
// 演示如何使用工廠模式初始化結構體
func struct3_sample3() {
var a *struct33 = create_struct33("webabcd")
a.age = 40
fmt.Println(a) // &{webabcd 40}
}
type struct33 struct {
name string
age int
}
// 工廠模式
func create_struct33(name string) *struct33 {
return &struct33{
name: name,
}
}
速戰速決 go https://github.com/webabcd/GoSample
作者 webabcd