-3

I am coming from javascript and know how to check if a variable exists. We can use !!var

I have come across an array in Go where I want to know if an index exists:

myArr := []int{1, 2, 3}

if myArr[3] {
  fmt.Println("YES")
}

When I run this it gives me an error: Index Out Of Range: 3

Highway of Life
  • 22,803
  • 16
  • 52
  • 80

1 Answers1

6

Since Go is a compiled language the concept of a variable not existing does not make sense. The closest thing is that some types can take a nil value.

As far as arrays go they just have a length (without gaps). So if the length is N then only indices 0 to N-1 are valid. The built-in len() function works with any array or slice.

AJR
  • 1,547
  • 5
  • 16
  • 2
    "Since Go is a statically typed language the concept of a variable not existing does not make sense" - this has nothing to do with static typing. Static typing says you know what type any given value is at compile time, it has nothing to do with whether it exists at all. – Adrian Feb 11 '20 at 15:07
  • Thanks @Adrian, you are right. I adjusted my answer accordingly. – AJR Oct 01 '20 at 11:06