Go language warnings and errors

后端 未结 4 1110
刺人心
刺人心 2021-02-19 18:08

It seems that GO language does not have warnings in it. I\'ve observed few instances. 1. \"declared and not used\"(if variable is declared and not used anywhere it gives an e

4条回答
  •  心在旅途
    2021-02-19 18:55

    The Go Programming Language FAQ

    Can I stop these complaints about my unused variable/import?

    The presence of an unused variable may indicate a bug, while unused imports just slow down compilation. Accumulate enough unused imports in your code tree and things can get very slow. For these reasons, Go allows neither.

    When developing code, it's common to create these situations temporarily and it can be annoying to have to edit them out before the program will compile.

    Some have asked for a compiler option to turn those checks off or at least reduce them to warnings. Such an option has not been added, though, because compiler options should not affect the semantics of the language and because the Go compiler does not report warnings, only errors that prevent compilation.

    There are two reasons for having no warnings. First, if it's worth complaining about, it's worth fixing in the code. (And if it's not worth fixing, it's not worth mentioning.) Second, having the compiler generate warnings encourages the implementation to warn about weak cases that can make compilation noisy, masking real errors that should be fixed.

    It's easy to address the situation, though. Use the blank identifier to let unused things persist while you're developing.

    import "unused"
    
    // This declaration marks the import as used by referencing an
    // item from the package.
    var _ = unused.Item  // TODO: Delete before committing!
    
    func main() {
        debugData := debug.Profile()
        _ = debugData // Used only during debugging.
        ....
    }
    

提交回复
热议问题