As you are seeing, Go does not allow you to do a naked return when one of
the named return values is being shadowed by another variable. If you take
a look at the "Return statements" section in the Go Language Specification
[1], it mentions this restriction:

> Implementation restriction: A compiler may disallow an empty expression
list in a "return" statement if a different entity (constant, type, or
variable) with the same name as a result parameter is in scope at the place
of the return.

On line 203, it may look like err is being shadowed here, but it's not. The
:= operator will only define a new variable if a variable with that same
name hasn't already been defined in the same stack frame. On line 200,
m3u8List is being defined, but err is simply being assigned a new value.
This is because err is already defined in this stack frame in the form of a
named return variable.

On line 210, we're now in a new stack frame. Because of that, it is now
possible to redefine the err variable by shadowing the one defined as a
named return in the previous stack frame. Now that a named return variable
is being shadowed, naked returns will no longer compile. It's the rules :)

On line 216, we're no longer using a naked return, so the rule about
shadowing no longer applies.

As for why this restriction is in place, I'm not sure. I would be
interested to hear an explanation. However, I would assume it's to reduce
confusion. Naked returns can already be confusing, and adding shadowing
into the mix could make it very difficult to figure out what values are
actually being returned.

1. https://golang.org/ref/spec#Return_statements

On Tue, Nov 27, 2018 at 7:03 PM hui zhang <fastfad...@gmail.com> wrote:

> happen in  go 1.10.2   1.11.2
>
> 在 2018年11月28日星期三 UTC+8上午11:02:47,hui zhang写道:
>>
>> ./main.go:212:4: err is shadowed during return
>>
>> check code above only line 212 report err
>> however line 203 and 212 are almost the same case. but did not report err.
>>
> --
> 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.
> For more options, visit https://groups.google.com/d/optout.
>


-- 
Tyler Compton
Student of Software Engineering
Arizona State University

-- 
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.
For more options, visit https://groups.google.com/d/optout.

Reply via email to