Skip to content

Instantly share code, notes, and snippets.

@Hypnotriod
Last active June 27, 2026 14:12
Show Gist options
  • Select an option

  • Save Hypnotriod/2e2d13a724a98d968353d041a0e550c5 to your computer and use it in GitHub Desktop.

Select an option

Save Hypnotriod/2e2d13a724a98d968353d041a0e550c5 to your computer and use it in GitHub Desktop.
Go "checked" two-value assignment for the slices, arrays and nested structures proposal

The standard Maps behavior

func main() {
	var m map[int]int
	v, ok := m[0] // v = 0, ok = false
}

Issue: Slices and Arrays out of range access

func main() {
	i := 0
	var s []int
	v := s[i] // panic: runtime error: index out of range [0] with length 0
	
	a := [0]int{}
	v = a[i] // panic: runtime error: index out of range [0] with length 0
}

Solution: Use Maps two-value assignment approach for Slices and Arrays

func main() {
	i := 0
	var s []int
	v, ok := s[i] // v = 0, ok = false
	
	a := [0]int{}
	v, ok = a[0] // v = 0, ok = false
}

Issue: nil pointer dereference

func main() {
	var i *int
	v := *i // panic: runtime error: invalid memory address or nil pointer dereference
}

Solution: Extrapolate the approach

func main() {
	var i *int
	v, ok := *i // v = 0, ok = false
}

Issue: nil pointer dereference in nested structures

type A struct {
	b *B
}

type B struct {
	c int
}

func main() {
	a := A{b: &B{c: 1}}
	c := a.b.c // c = 1

	a = A{b: nil}
	c = a.b.c // panic: runtime error: invalid memory address or nil pointer dereference
}

Solution: Use similar approach when accessing nested structures

func main() {
	a := A{b: nil}
	c, ok := a.b.c // c = 0, ok = false
}

More examples

type A struct {
	b *B
}

type B struct {
	c *int
	s []int
	m map[int]string
}

func main() {
	i := 1
	a := A{b: &B{c: &i, s: []int{1}, m: map[int]string{0: "zero"}}}
	c, ok := *a.b.c // c = 1, ok = true
	cPtr, ok := a.b.c // cPtr = 0x1234abcd, ok = true
	s0, ok := a.b.s[0] // s0 = 1, ok = true
	m0, ok := a.b.m[0] // m0 = "zero", ok = true
	
	a = A{b: &B{c: nil, s: nil, m: nil}}
	c, ok = *a.b.c // c = 0, ok = false
	cPtr, ok = a.b.c // cPtr = <nil>, ok = true
	s0, ok = a.b.s[0] // s0 = 0, ok = false
	m0, ok = a.b.m[0] // m0 = "", ok = false
	
	a = A{b: nil}
	c, ok = *a.b.c // c = 0, ok = false
	cPtr, ok = a.b.c // cPtr = <nil>, ok = false
	s0, ok = a.b.s[0] // s0 = 0, ok = false
	m0, ok = a.b.m[0] // m0 = "", ok = false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment