SoFunction
Updated on 2025-03-05

How to determine whether an element in an array exists (isset)

For example, it is now necessary to determine whether the command line has passed parameters, that is, whether [1] exists

If the following judgment is used:

package main 
import (
 "fmt"
 "os"
)
 
func main() {
 if [1] != "" {
  ("aaa")
 } else {
  ("bbb")
 } 
}

An error will be reported: index out of range

panic: runtime error: index out of range
 
goroutine 1 [running]:
()
 /root/workspace/go/:9 +0x100
exit status 2

Correct way to deal with it:

Through traversal, determine whether key = 1 exists

package main 
import (
 "fmt"
 "os"
)
 
func main() {
 var target string                             // Used to obtain the final required [1] for k, v := range() {
  if k == 1 {                               // Assume that you need to obtain [k], k = 1   target = v
  }
 } 
 
 if target != "" {                             // Not empty means [1] exists  ("[1] = %s", target)     
 }
}

Supplement: Regular match in golang & determine whether the element is in slice or array

1. Regular matching

package main 
import (
 "fmt"
 "regexp"
) 

func main() { 
    //pattern := "\\d+" //Backslashes need to be escaped pattern := "[a-zA-Z]"   //Match letters str := "a1.22.35.4"
 result, _ := (pattern, str)
 (result)   //true
}

2. Determine whether the element is in a slice or an array

package main 
import "fmt" 
import "/wxnacy/wgo/arrays" 
//go get /wxnacy/wgo/arrays installation package
func main() {
 str := "342"
 var numbers []string
 numbers = append(numbers, "3332", "342", "ssddd", "ssss", "%%%%") 
 index := (numbers, str)
 if index == -1 {
  ("not exists") //-1 means that it does not exist } else {
  (index) //If it exists, it will return the subscript of the element }
}

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.