V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
yujianwjj
V2EX  ›  Go 编程语言

go 结构体内嵌接口的疑问

  •  
  •   yujianwjj · 2021-03-19 14:43:36 +08:00 · 1541 次点击
    这是一个创建于 1105 天前的主题,其中的信息可能已经有所发展或是发生改变。
    func TestInterface(t *testing.T) {
    	type Reader interface {
    		Read()
    	}
    	type Cache struct {
    		Reader
    	}
    	c := Cache{}
    	c.Read()
    }
    

    以上代码会报空指针错误。

    我的疑问是,有没有办法在编译的时候就能够主动的发现这个错误。

    10 条回复    2021-03-20 14:25:58 +08:00
    baiyi
        1
    baiyi  
       2021-03-19 15:01:31 +08:00
    结构体如果是实现接口,可以通过 var _ Reader = Cache{} 来发现。

    内嵌只能通过 if c.Reader != nil 来判断了吧,编译器并不知道你在哪里赋值了。
    hwdef
        2
    hwdef  
       2021-03-19 15:10:00 +08:00
    https://github.com/xxjwxc/uber_go_guide_cn

    可以看看 uber 的 go 风格指南,我记得有写
    Mark3K
        3
    Mark3K  
       2021-03-19 15:12:26 +08:00
    内嵌 interface 的目的是啥
    rrfeng
        4
    rrfeng  
       2021-03-19 15:16:32 +08:00
    你这个
    type Cache struct {
    Reader
    }
    等于
    type Cache struct {
    Reader Reader
    }

    然后 Cache{} 初始化时,接口类型默认值是 nil,所以 Reader 是 nil

    跟下面一个道理(指针类型的默认值是 nil )
    type Cache Struct {
    Something *int
    }


    所以,无解。通常写一个 NewCache() 方法生成可以避免。
    kele1997
        5
    kele1997  
       2021-03-19 15:20:03 +08:00
    `var _ Reader = (*Cache)(nil)`
    kele1997
        6
    kele1997  
       2021-03-19 15:27:00 +08:00
    不好意思,俺上面的写法是针对,实现接口的。你问题里面的是直接继承接口。
    不过你可以不继承接口,然后使用下面的代码来实现

    ```
    func TestInterface(t *testing.T) {
    type Reader interface {
    Read()
    }
    type Cache struct {
    }


    var _ Reader = (*Cache)(nil)
    c := Cache{}
    c.Read()
    }
    ```
    janxin
        7
    janxin  
       2021-03-19 15:29:43 +08:00
    @rrfeng 正解,不过即便写了 NewCache()也没法杜绝 SB 用户这么用🤦‍♂️
    nuk
        8
    nuk  
       2021-03-19 15:38:15 +08:00
    不能,所以不要把 interface 嵌入 struct
    fenghuang
        9
    fenghuang  
       2021-03-19 23:22:54 +08:00
    把 struct 匿名嵌套在 struct 也会出现这种情况
    qwertyzzz
        10
    qwertyzzz  
       2021-03-20 14:25:58 +08:00
    这个问题我怎么在哪见过啊
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5308 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 05:59 · PVG 13:59 · LAX 22:59 · JFK 01:59
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.