4 ms·
Go handles dead code by not allowing you to compile something with dead code. In the examples the "_ =" is needed to force it to compile and do the work without
by JamesMcMinn 10y ago
Go handles dead code by not allowing you to compile something with dead code. In the examples the "_ =" is needed to force it to compile and do the work without actually assigning the value to anything.
- junke 10y agoSuppose you "go generate" code which ends up having something along the lines of: x := true var y = 0 if x { y = 10 } else { y = 20 } In that case dead code elimination might require a little more analysis than checking for unassigned expressions and unused variables. So the question might be: what kind of dead code elimination exist in the compiler, apart from what you describe which has existed since the beginning of Go? (if I understand correctly)
- fizzbatter 10y agoPerhaps i misunderstand you, but isn't simply calling a function the same as what you quoted? Eg, `_ := Foo()` is the same as `Foo()`. No assignment needed. `_` mainly exists to allow ignoring single values, within multiple. Eg, dropping an error: `val, _ := MightError()`
- JamesMcMinn 10y agoFoo() can have side-effects, taking a value from an array cannot, so Foo() is not necessarily dead code, whilst a[0] certainly is. _ serves multiple purposes, not just for ignoring a return value. It's often used when you care about the side effect but not the return value, such as importation a driver for a database . You'll never use the library, so you import it as _ "db.driver.name/path/".
- euyyn 10y agoCan't taking a value from an array result in a panic? Quite the side effect.
- chrisseaton 10y ago> Go handles dead code by not allowing you to compile something with dead code. This is obviously not true and is easily disproved. Here's a program that compiles but has statically provably dead code on line 15 https://play.golang.org/p/_XcxezHV-6 https://play.golang.org/p/_XcxezHV-6. But even if I couldn't give you an example like that where the dead code is obvious, dead code is produced by the compiler itself as it optimises, and by code generation tools.