dongxu3029 2016-01-23 15:43
浏览 54
已采纳

Go中本地范围的“变量声明”和“短变量声明”之间的区别

According to this question how-to-define-a-single-byte-variable-in-go-lang

At a local scope:

var c byte = 'A' 

and

c := byte('A')

My questions are:

  1. Do they have the same mechanism?
  2. Which one is more easy to understand by a go compiler?
  • 写回答

1条回答 默认 最新

  • doulu4976 2016-01-23 15:54
    关注

    They are the same type (byte is an alias for uint8) and value. For example,

    package main
    
    import "fmt"
    
    func main() {
        var c byte = 'A'
        d := byte('A')
        fmt.Printf("c: %[1]T %[1]v d: %[2]T %[2]v c==d: %v", c, d, c == d)
    }
    

    Output:

    c: uint8 65 d: uint8 65 c==d: true
    

    They are equally efficient; the runtime code is the same. They are both easy to understand by Go compilers.

    The Go Programming Language Specification.

    A short variable declaration uses the syntax:

    ShortVarDecl = IdentifierList ":=" ExpressionList .
    

    It is shorthand for a regular variable declaration with initializer expressions but no types:

    "var" IdentifierList = ExpressionList .
    

    The "best" is a matter of style. Which reads better in a given context?

    The Go Programming Language

    Alan A. A. Donovan · Brian W.Kernighan

    Because of their brevity and flexibility, short variable declarations are used to declare and initialize the majority of local variables. A var declaration tends to be reserved for local variables that need an explicit type that differs from that of the initializer expression, or for when the variable will be assigned a value later and its initial value is unimportant.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥15 帮我写一个c++工程