面向结构、面向对象之异同
//结构化程序设计int main () {int count;int money;int type;scanf (“%d %d %d”, &count, &money, &type);if (type)printf (“%d”, count – money);elseprintf (“%d”, count + money);}//面向对象程序设计class Count {int count;Count (int count) {this.count = count;}int save (int money) {count += money;}int take (int money) {if(count >= money)count -= money;}}
Golang面向对象和接口编程
type Node struct {Value intLeft *NodeRight *Node}func (node *Node) SetValue(value int) {node.Value = value}func (node *Node) Traverse() {if node == nil {return}node.Left.Traverse()node.Print()node.Right.Traverse()}func (node *Node) Print() {fmt.Print(node.Value, ” “)}
对象初始化
var root tree.Noderoot.SetValue(8)root.Left = &tree.Node{}root.Right = &tree.Node{5, nil, nil}root.Right.Left = new(tree.Node)root.Left.Right = new(tree.Node)root.Left.Right.SetValue(6)root.Right.Left.SetValue(4)root.Traverse() // 0,6,8,4,5
package queuetype Queue []interface{}func (q *Queue) Push(obj interface{}) {*q = append(*q, obj)}func (q *Queue) Pop() interface{} {if q.IsEmpty() {return nil}head := (*q)[0]*q = (*q)[1:]return head}func (q *Queue) IsEmpty() bool {return len(*q) <= 0}func main() {queue := Queue{}queue.Push(“Hello”)queue.Push(1)queue.Push(1.5)queue.Push(true)fmt.Println(queue.Pop())fmt.Println(queue.Pop())fmt.Println(queue.IsEmpty())fmt.Println(queue.Pop())fmt.Println(queue.Pop())fmt.Println(queue.IsEmpty())}
// 组合方式扩展type myNode struct {node *tree.Node}// 扩展:前序遍历func (node *myNode) preOrder() {if node == nil || node.node == nil {return}node.node.Print()left := myNode{node.node.Left}right := myNode{node.node.Right}left.preOrder()right.preOrder()}
type Human struct {Name stringAge int}func (Human) Speak() {fmt.Println(“Hello!”)}type Teacher struct {HumanName stringSchool stringSubject string}func (t Teacher) Speak() {fmt.Printf(“My name is %s, I teach %s”, t.Name, t.Subject)}func main() {t := Teacher{Human: Human{“Bob”,18,},Name: “John”,School: “MIT”,Subject: “CS”,}// My name is John, I teach CSt.Speak()}
type Student struct {h Human //非匿名字段school string}
type Reader interface {Read(p []byte) (n int, err error)}type Writer interface {Write(p []byte) (n int, err error)}type ReadWriter interface {ReaderWriter}