前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >go 语言的一个赋值操作

go 语言的一个赋值操作

作者头像
charlieroro
发布2020-03-23 16:42:50
5690
发布2020-03-23 16:42:50
举报
文章被收录于专栏:charlieroro

最近在看client-go源码,在源码的\tools\caches\store.go文件中有一行代码不得其解(如下标黄内容),它将一个struct赋值给了一个interface

代码语言:javascript
复制
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接口

下述代码是可以运行的

代码语言:javascript
复制
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)
}

但下述是不可以运行的

代码语言:javascript
复制
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{}

报出的错误如下:

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

该语法实际就是实现了某结构必须实现某接口的强制要求

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-06-14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档