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

go 全局变量的一个疑问?

  •  1
     
  •   yujianwjj · 2021-03-18 15:41:19 +08:00 · 1415 次点击
    这是一个创建于 1106 天前的主题,其中的信息可能已经有所发展或是发生改变。

    看别人写的 go 代码里面,经常在文件开头定义一些空的全局变量

    var _ XX = XX{}
    

    请问这有啥用?

    5 条回复    2021-03-21 10:10:54 +08:00
    westoy
        1
    westoy  
       2021-03-18 15:54:30 +08:00   ❤️ 2
    就是为了没啥用用的

    开发的时候导入一个很可能用到的包, 但是一开始根本没用到, 总不能为了不报 unused import 的错, 每次编译都改来改去吧, 就直接让它没啥用一下.....
    kaibmlddallyson6
        2
    kaibmlddallyson6  
       2021-03-18 15:56:24 +08:00
    参考 uber go 规范
    baiyi
        3
    baiyi  
       2021-03-18 15:57:24 +08:00   ❤️ 6
    一般应该是 “var _ Client = &kubernetesClient{}” 或者 “var _ Client = (*kubernetesClient)(nil)” 的形式。

    主要是为了快速查看 kubernetesClient 是否实现了 Client 的接口。
    SSang
        4
    SSang  
       2021-03-19 17:45:04 +08:00
    主要是用来保证 interface 的实现是完整的吧,因为如果实例没有完全实现接口是可以编译过去的,但是加了这个就编译不过去了

    比如这样是没问题的,但是其实你可能是想要实现 `TestInterface`,这么写也不会给你报错,但和预期结果就不一样了

    ```go
    type TestInterface interface {
    func1()
    func2()
    }

    type test struct {
    }

    func (t *test) func1() {
    }
    ```

    这样写就会有报错了

    ```go
    type TestInterface interface {
    func1()
    func2()
    }

    var _ TestInterface = test{}

    type test struct {
    }

    func (t *test) func1() {
    }
    ```

    ```
    Cannot use 'test{}' (type test) as type TestInterface Type does not implement 'TestInterface' as some methods are missing: func2()
    ```
    outyua
        5
    outyua  
       2021-03-21 10:10:54 +08:00
    1 楼正解, 这句话并不是告诉编译器 XX 实现了 XX
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5239 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 07:23 · PVG 15:23 · LAX 00:23 · JFK 03:23
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.