Go 其七 空接口與斷言

空接口與斷言

  1. 空接口可以表示任何類型
  2. 通過斷言來將空接口轉換爲定製類型
  v, ok := p.(int) //ok=true時轉換成功

  

Go接口最佳實踐
傾向於使用更小的接口,很多接口只包含一個方法,目的是讓實現者負擔更小
例如

type Reader interface {
    Read(p []byte) (n int, err error)
}

type Writer interface {
    Write(p []byte) (n int, err error)
}

  

較大的接口定義,可以由多個小接口定義組合而成
例如:

type ReadWrite interface {
    Reader
    Writer
}

  



只依賴於必要功能的最小接口
例如:

func StoreData(reader Reader) error {
  ...
}

  

相關代碼如下:

package empty_interface

import (
	"testing"
	"fmt"
)

func DoSomething(p interface{}){
	// if i,ok:=p.(int); ok{
	// 	fmt.Println("Integer", i)
	// 	return
	// }
	// if i,ok:=p.(string); ok{
	// 	fmt.Println("string", i)
	// 	return
	// }

	// fmt.Println("Unknow Type")

	//使用switch簡化上面的結構
	switch v:=p.(type){
		case int:
			fmt.Println("Integer", v)
		case string:
			fmt.Println("string", v)
		default:
			fmt.Println("Unknow Type")
	}

	return
}

func TestEmptyInterfaceAssertion(t *testing.T){
	DoSomething(10)
	DoSomething("15")
	DoSomething('z')
}

 

  執行結果爲:

=== RUN   TestEmptyInterfaceAssertion
Integer 10
string 15
Unknow Type
--- PASS: TestEmptyInterfaceAssertion (0.00s)
PASS
coverage: [no statements]
ok  	Session13/empty_interface	0.261s	coverage: [no statements]

  有些泛型的味道了~~

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章