英文:
Difference between "variable declaration" and "short variable declaration" at local scope in Go
问题
根据这个问题 how-to-define-a-single-byte-variable-in-go-lang
在局部作用域中:
var c byte = 'A'
和
c := byte('A')
我的问题是:
- 它们有相同的机制吗?
- 哪一个更容易被 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:
- Do they have the same mechanism?
- Which one is more easy to understand by a go compiler?
答案1
得分: 3
它们是相同类型的(byte
是 uint8
的别名)且具有相同的值。例如,
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 编译器理解。
短变量声明的语法如下:
ShortVarDecl = IdentifierList ":=" ExpressionList .
它是使用初始化表达式但没有类型的常规变量声明的简写形式:
"var" IdentifierList = ExpressionList 。
哪种方式更好是一个风格问题。在给定的上下文中,哪种方式更易读?
Alan A. A. Donovan · Brian W.Kernighan
由于简洁和灵活性,短变量声明被用于声明和初始化大多数局部变量。
var
声明通常用于需要与初始化表达式的类型不同的局部变量,或者当变量稍后将被赋值一个值且其初始值不重要时。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论