The Go Programming Language
› http://golang.org/
› Go Playground
Go Projects
› Revel Web Framework
yujianwjj

go 结构体内嵌接口的疑问

  •  
  •   yujianwjj · Mar 19, 2021 · 2779 views
    This topic created in 2078 days ago, the information mentioned may be changed or developed.
    func TestInterface(t *testing.T) {
    	type Reader interface {
    		Read()
    	}
    	type Cache struct {
    		Reader
    	}
    	c := Cache{}
    	c.Read()
    }
    

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

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

    10 replies  •  2021-03-20 14:25:58 +08:00
    FinnBai
    FinnBai
    Mar 19, 2021
    1
    结构体如果是实现接口,可以通过 var _ Reader = Cache{} 来发现。

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

    可以看看 uber 的 go 风格指南,我记得有写
    Mark3K
    Mark3K
    Mar 19, 2021
    3
    内嵌 interface 的目的是啥
    rrfeng
    rrfeng
    Mar 19, 2021
    4
    你这个
    type Cache struct {
    Reader
    }
    等于
    type Cache struct {
    Reader Reader
    }

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

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


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

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


    var _ Reader = (*Cache)(nil)
    c := Cache{}
    c.Read()
    }
    ```
    janxin
    janxin
    Mar 19, 2021
    7
    @rrfeng 正解,不过即便写了 NewCache()也没法杜绝 SB 用户这么用🤦‍♂️
    nuk
    nuk
    Mar 19, 2021
    8
    不能,所以不要把 interface 嵌入 struct
    fenghuang
    fenghuang
    Mar 19, 2021
    9
    把 struct 匿名嵌套在 struct 也会出现这种情况
    asLw0P981N0M0TCC
    asLw0P981N0M0TCC
    Mar 20, 2021
    10
    这个问题我怎么在哪见过啊
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   3640 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 09:54 · PVG 17:54 · LAX 01:54 · JFK 04:54
    ♥ Do have faith in what you're doing.