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

huangapple go评论90阅读模式
英文:

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

我的问题是:

  1. 它们有相同的机制吗?
  2. 哪一个更容易被 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

得分: 3

它们是相同类型的(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 编译器理解。

Go 编程语言规范

短变量声明的语法如下:

ShortVarDecl = IdentifierList ":=" ExpressionList .

它是使用初始化表达式但没有类型的常规变量声明的简写形式:

"var" IdentifierList = ExpressionList 。

哪种方式更好是一个风格问题。在给定的上下文中,哪种方式更易读?

Go 编程语言

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.

huangapple
  • 本文由 发表于 2016年1月23日 23:43:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/34965414.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定