23 Apr 2023 05:31:25 jlfo...@berkeley.edu <jlforr...@berkeley.edu>:


> 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
>
...
>
> I doubt if this note will change anybody’s mind but it’s something to think 
> about.
>

I agree with OP and probably this is one of the unpopular opinion about Go 
style.

My reasoning is based on three things [1]. First, readability, as also pointed 
out by OP.  Given the following statement

t := f()

If you are new to code base, you need to know the signature of f to know the 
type of t. To minimize back and forth when reading code, it is better to 
declare the type of t before or along with assignment. Yes, some advanced IDE 
may provide clickable link, unfortunately not all of us use IDE when developing 
Go.

Second, minimize local, temporary variables.

Third, prevent subtle bugs [2][3][4] caused by shadowing.

For a long term code base, I try to enforce the variable to be declared 
explicitly with downside more line of codes.

[1] 
https://kilabit.info/journal/2017/05/Go_Informal_Coding_Style#avoid______if_possible
[2] https://github.com/golang/go/issues/377
[3] https://github.com/golang/go/issues/20733
[4] https://github.com/golang/go/issues/21291

-- 
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 golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/3110d5fb-37e5-4654-a373-df9b480832b5%40gmail.com.

Reply via email to