Go 中局部作用域 "variable declaration" 和 "short variable declaration" 的区别

Difference between "variable declaration" and "short variable declaration" at local scope in Go

根据这个问题

在本地范围内:

var c byte = 'A' 

c := byte('A')

我的问题是:

  1. 他们有相同的机制吗?
  2. 哪个更容易被go编译器理解?

它们是相同的类型(byteuint8 的别名)和值。例如,

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)
}

输出:

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

它们同样高效;运行时代码是相同的。它们都很容易被 Go 编译器理解。

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 .

"best" 是风格问题。在给定的上下文中哪个读起来更好?

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.