As a beginning Go programmer, I was initially attracted to the short
variable declaration syntax.
It’s great for declaring variables of a simple type. What could be wrong
with letting the Go compiler infer a variable type by looking at what’s
being assigned to the variable, such as:
func main() {
x := 10
}
Nothing. This is trivially the same as
func main() {
var x int
x = 10
}
I didn’t have to waste my precious time by entering an explicit type
declaration for “x” when the compiler already knew what it was.
But what about something like
import “os”
func main() {
file, _ := os.Open(os.Args[1])
}
Again, nothing is wrong, at least not until I have to pass “file” to
another function. For example
import “os”
func main() {
file, _ := os.Open(os.Args[1])
myfunc(file)
}
func myfunc(file ???) {
}
What type should I use to declare “file” in the parameter list for
myfunc()? As a new Go programmer I have to admit that I haven’t memorized
all the types used in the Go standard library. So, I have to break off
working on myfunc() to look up the type returned by os.Open(). This isn’t a
huge deal, but it’s a distraction and can waste time. I suppose that as I
gain experience with Go, I’ll have to do this less and less.
But, it doesn’t matter how experienced I am with Go when I start using
user-defined types from packages that aren’t in the Go standard library.
For example (from Ben Hoyt’s excellent goawk program):
import "github.com/benhoyt/goawk/parser"
func main() {
prog, err := parser.ParseProgram(fileReader.Source(), parserConfig)
myfunc(prog)
}
func myfunc(prog ???) {
}
Since I’m going to have to look up the returned types of parse.ParseProgram
anyway, what’s the advantage of using a short variable declaration? They
just delay the inevitable.
Short definitions detract from one of Go’s primary goals - readability. I
started using Go in the first place because I wanted a strongly typed
language with explicit type declarations.
As a result of all this, I’ve started to avoid short variable declarations,
except when I’m initializing a variable inside an "if"
<https://go.dev/ref/spec#If_statements>, "for"
<https://go.dev/ref/spec#For_statements>, or "switch
<https://go.dev/ref/spec#Switch_statements>” statement, such as
if v := math.Pow(x, n); v < lim {
}
for i := 0; i < 10; i++ {
}
switch os := runtime.GOOS; os {
}
In these cases I have no choice if I want to declare local temporary
variables since long declarations aren’t syntactically allowed.
I doubt if this note will change anybody’s mind but it’s something to think
about.
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/b156477f-0ab2-4207-8df2-bd1ceb2cf39cn%40googlegroups.com.