Skip to content

Instantly share code, notes, and snippets.

@pote
Last active August 29, 2015 13:56
Show Gist options
  • Save pote/8831889 to your computer and use it in GitHub Desktop.
Save pote/8831889 to your computer and use it in GitHub Desktop.
Adventure in variable scoping
Hyrule ~/code/tmp
▸ go run scoping.go
./scoping.go:14: variable is shadowed during return
func MyFunction(name string, someAmount int) (someCrazyNumber int, processedString string, err error) {
someCrazyNumber = 4 // 1*
err = SomeFunctionThatMightFailButWont() // 2*
//...
return // 3*
}
function test_function()
local variable
variable = 'original value'
if true then
local variable
variable = 'altered value'
end
print(variable)
end
test_function() --> 'original value'
def function():
variable = "original value"
if True:
variable = "altered value"
print(variable)
function() #=> "altered value"
def another_function():
variable = "original value"
def nested_function():
variable = "altered value"
nested_function()
print(variable)
another_function() #=> "original value"
def yet_another_function():
variable = "original value"
def nested_function():
nonlocal variable
variable = "altered value"
nested_function()
print(variable)
yet_another_function() #=> "altered value"
def function
variable = "original value"
if true
variable = "altered value"
end
puts variable
end
function #=> "altered value"
func testCase1() {
var variable string
variable = "original value"
if true {
variable = "altered value"
}
fmt.Println(variable) //=> "altered value"
}
func testCase2() {
var variable string
variable = "original value"
if true {
var variable string
variable = "altered value"
fmt.Println("inner scope")
fmt.Println(variable) //=> "altered value"
}
fmt.Println("outer scope")
fmt.Println(variable) //=> "original value"
}
func testCase1NestedNamedReturn() (variable string) {
variable = "original value"
if true {
var variable string
variable = "altered value"
return
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment