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

golang 里面全局匿名变量的作用是啥?

  •  
  •   iCD · Sep 10, 2020 · 3437 views
    This topic created in 2085 days ago, the information mentioned may be changed or developed.

    看到过好几次别人的代码里面都有全局的匿名变量,比如这里:

    ...
    
    type cachedWriter struct {
    	gin.ResponseWriter
    	status  int
    	written bool
    	store   persistence.CacheStore
    	expire  time.Duration
    	key     string
    }
    
    var _ gin.ResponseWriter = &cachedWriter{}
    ...
    
    

    代码地址:https://github.com/gin-contrib/cache/blob/master/cache.go#L45

    这里 var _ gin.ResponseWriter = &cachedWriter{} 这样写是为了啥,没看明白,求赐教~

    9 replies    2020-09-15 11:28:27 +08:00
    imgk
        1
    imgk  
       Sep 10, 2020 via iPhone   ❤️ 6
    确定 cacheWriter 实现接口
    zengming00
        2
    zengming00  
       Sep 10, 2020
    ```go
    type myInterface interface {
    foo()
    }

    type myData struct{}

    func (o *myData) foo() {
    }

    var _ myInterface = &myData{}

    ```
    1 楼说得对,如果没有实现 myInterface 接口,那么在编译阶段就会报错
    iCD
        3
    iCD  
    OP
       Sep 10, 2020
    原来如此,我学会了!
    useben
        4
    useben  
       Sep 11, 2020
    在挺多开源框架见到, 确实技巧了. 不过用 goland 的话, 可以一键某结构实现某接口, 可以避免这样的检验了
    weakish
        5
    weakish  
       Sep 11, 2020   ❤️ 1
    githubhaoliu
        6
    githubhaoliu  
       Sep 11, 2020
    还有一些是为了跳过 unused 检测,比如

    var _ = xxx
    buzz2d0
        7
    buzz2d0  
       Sep 11, 2020
    学习了
    securityCoding
        8
    securityCoding  
       Sep 12, 2020
    学习了
    schwarzeni00
        9
    schwarzeni00  
       Sep 15, 2020
    我刚想发个新帖子问这个问题的,就看到这个帖子了。在看 client-go 源码的时候也看到这种用法了

    ```go
    var _ RateLimiter = &ItemFastSlowRateLimiter{}
    ```
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3081 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 52ms · UTC 13:58 · PVG 21:58 · LAX 06:58 · JFK 09:58
    ♥ Do have faith in what you're doing.