go 語言的一個賦值操做

 最近在看client-go源碼,在源碼的\tools\caches\store.go文件中有一行代碼不得其解(以下標黃內容),它將一個struct賦值給了一個interfacegolang

type Store interface {
    Add(obj interface{}) error
    Update(obj interface{}) error
    Delete(obj interface{}) error
    List() []interface{}
    ListKeys() []string
    Get(obj interface{}) (item interface{}, exists bool, err error)
    GetByKey(key string) (item interface{}, exists bool, err error)

    // Replace will delete the contents of the store, using instead the
    // given list. Store takes ownership of the list, you should not reference
    // it after calling this function.
    Replace([]interface{}, string) error
    Resync() error
}

type cache struct {
    // cacheStorage bears the burden of thread safety for the cache
    cacheStorage ThreadSafeStore
    // keyFunc is used to make the key for objects stored in and retrieved from items, and
    // should be deterministic.
    keyFunc KeyFunc
}

var _ Store = &cache{}

google搜索後沒有獲得結果,在stackoverflow上提交了一個問題golang syntax in client-go,很快就獲得了回答(老外自由時間果真比較多^^),「var _ Store = &cache{}」的做用是強制要求cache結構實現Store接口。測試

作個測試,TestSt實現了TestIf接口中的一個方法write,但因爲沒有實現read,則其並無實現TestIf接口this

下述代碼是能夠運行的google

package main

import "fmt"

type TestIf interface {
    write(w string)
    read()
}

type TestSt struct {

}

func (t *TestSt)write(w string){
    fmt.Println("write")
}

func main() {
    fmt.Println(111)
}

但下述是不能夠運行的spa

package main

import "fmt"

type TestIf interface {
    write(w string)
    read()
}

type TestSt struct {

}

func (t *TestSt)write(w string){
    fmt.Println("write")
}

var _ TestIf=&TestSt{}
func main() { 
fmt.Println(
111)
}

報出的錯誤以下:code

Cannot use '&TestSt{}' (type *TestSt) as type TestIf in assignment Type does not implement 'TestIf' as some methods are missing: read() more... (Ctrl+F1)

該語法實際就是實現了某結構必須實現某接口的強制要求blog

相關文章
相關標籤/搜索