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

go 全局变量的一个疑问?

  •  1
     
  •   yujianwjj · Mar 18, 2021 · 2064 views
    This topic created in 1887 days ago, the information mentioned may be changed or developed.

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

    var _ XX = XX{}
    

    请问这有啥用?

    5 replies    2021-03-21 10:10:54 +08:00
    westoy
        1
    westoy  
       Mar 18, 2021   ❤️ 2
    就是为了没啥用用的

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

    主要是为了快速查看 kubernetesClient 是否实现了 Client 的接口。
    SSang
        4
    SSang  
       Mar 19, 2021
    主要是用来保证 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  
       Mar 21, 2021
    1 楼正解, 这句话并不是告诉编译器 XX 实现了 XX
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3088 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 216ms · UTC 12:05 · PVG 20:05 · LAX 05:05 · JFK 08:05
    ♥ Do have faith in what you're doing.