Skip to content

Instantly share code, notes, and snippets.

@arya2004
Last active July 26, 2024 18:28
Show Gist options
  • Select an option

  • Save arya2004/3847026b50cda01442764a921e4bc6bc to your computer and use it in GitHub Desktop.

Select an option

Save arya2004/3847026b50cda01442764a921e4bc6bc to your computer and use it in GitHub Desktop.
Deep Dive into Closures in Go: Theoretical Foundations and Practical Applications
func outer() {
a := 10
if true {
b := 20
fmt.Println(a, b) // a and b are visible here
}
fmt.Println(a) // a is visible here
// fmt.Println(b) // b is not visible here, this would cause a compile error
}
int* createPointer() {
int x = 10;
return &x; // Unsafe: x is allocated on the stack
}
func createPointer() *int {
x := 10
return &x // Safe: x will be allocated on the heap
}
func fib() func() int {
a, b := 0, 1
return func() int {
a, b = b, a+b
return a
}
}
func main() {
a := 10
if true {
b := 20
{
c := 30
fmt.Println(a, b, c) // All three variables are visible here
}
// fmt.Println(c) // c is not visible here, this would cause a compile error
}
// fmt.Println(b) // b is not visible here, this would cause a compile error
fmt.Println(a) // Only a is visible here
}
func outer() {
x := 10
inner := func() {
fmt.Println(x) // Refers to x in outer
}
inner()
}
func main() {
x := 20
outer() // Prints 10, not 20
}
func main() {
for i := 0; i < 3; i++ {
go func() {
fmt.Println(i)
}()
}
time.Sleep(time.Second) // Give goroutines time to run
}
func main() {
for i := 0; i < 3; i++ {
j := i
go func() {
fmt.Println(j)
}()
}
time.Sleep(time.Second) // Give goroutines time to run
}
func main() {
people := []struct {
Name string
Age int
}{
{"Alice", 23},
{"Bob", 32},
{"Charlie", 28},
}
sort.Slice(people, func(i, j int) bool {
return people[i].Age < people[j].Age
})
fmt.Println(people)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment