Reputation: 4139
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:
Upvotes: 2
Views: 1092
Reputation: 166598
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?
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.
Upvotes: 3