go 語言的一個賦值操作


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

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接口

下述代碼是可以運行的

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)
}

但下述是不可以運行的

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)
}

報出的錯誤如下:

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

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM