Compilation process and unused-declared variables (func/package) levels

93 views
Skip to first unread message

Jad

unread,
Mar 2, 2021, 12:37:55 PM3/2/21
to golang-nuts
Hi,
I'm new to Go and I would like to understand why the compilation process, both the compiler and linker, does raise an error for a declared but not used variable at funcs level in order to ensure clean code while the linker does not raise this error during the build process for declared but not used variables at package level but treat them as 'dead code' and silently remove them.

I asked on other mediums. Specifically Go Forum and #Go-nuts IRC and some more experienced gophers said this might constitute a bug, at least at philosophical level as it doesn't directly affect the build process.

Best,
Jad



Artur Vianna

unread,
Mar 2, 2021, 1:20:21 PM3/2/21
to Jad, golang-nuts
Many packages expose useful variables that are not being used themselves, like useful defaults for example. I guess this would be an argument in favor of limiting this kind of behaviour to inside the functions.

A good example is image/color/pallete.

Also, there is some shenanigans on estimating the life of a variable that exists in global scope, but i'm still learning about compilers to say anything useful about this.

--
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...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/b13a26ae-5662-4b74-af2d-6c9e6dbeb425n%40googlegroups.com.

Ian Lance Taylor

unread,
Mar 2, 2021, 1:31:44 PM3/2/21
to Jad, golang-nuts
On Tue, Mar 2, 2021 at 9:37 AM Jad <d...@madi.se> wrote:
>
> I'm new to Go and I would like to understand why the compilation process, both the compiler and linker, does raise an error for a declared but not used variable at funcs level in order to ensure clean code while the linker does not raise this error during the build process for declared but not used variables at package level but treat them as 'dead code' and silently remove them.
>
> I asked on other mediums. Specifically Go Forum and #Go-nuts IRC and some more experienced gophers said this might constitute a bug, at least at philosophical level as it doesn't directly affect the build process.

Package scope variables can provide hooks for other packages (if the
variables are exported) or for debuggers to change program behavior.
There's no easy way for the compiler or linker to know whether this
might happen.

In particular the compiler (perhaps unfortunately) supports a
go:linkname directive that can reach into another package and refer to
a package-scope variable. This is generally not good practice but
there is existing code that does it.

Ian
Reply all
Reply to author
Forward
0 new messages