1. 程式人生 > >go語言實現介面,接受者應該是傳值還是傳引用(傳引用相容傳值)

go語言實現介面,接受者應該是傳值還是傳引用(傳引用相容傳值)

/*
go語言中給介面賦值的時候,物件如果是值(對於引用的接受者處理不了)
如果是指標,則可以自動實現值的處理
 */

package main

import "fmt"

//定義Integer型別
type Integer int

type LessAddInf interface{
	Less(n Integer) bool
	Add(n Integer) Integer
}

func (this Integer) Less(n Integer) bool{
	return this < n
}

func (this *Integer) Add(n Integer) Integer{
	*this += n
	return *this
}

type Computer struct{
	CPU string "計算器"
	Memory string "記憶體"
}

type Thing interface{
	Name() string
	Attribute() string
}

func (this Computer) Name() string  {
	return "Computer"
}

func (this *Computer) Attribute()string  {
	return fmt.Sprintf("CPU=%v Memory=%v", this.CPU, this.Memory)
}

func main()  {
	var inf LessAddInf
	var n Integer
	inf = &n
	fmt.Printf("inf.Less(20)=%v\n",inf.Less(20))
	fmt.Printf("inf.Add(30)=%v\n", inf.Add(30))

	var thing Thing
	var computer = Computer{CPU:"英特爾至強-v3440", Memory:"三星DDR4(8g)"}
	thing = &computer
	fmt.Printf("thing.Name()=%v\n", thing.Name())
	fmt.Printf("thing.Attribute()=%v\n", thing.Attribute())
}