Home > Enterprise >  Golang - the differences between 'A' and A with same type string?
Golang - the differences between 'A' and A with same type string?

Time:12-30

I am working on an exercise that checks if any letter of a string is in an array of letters.

Here is my code so far:

func main() {
    one_point := []string {"A", "D", "F"}
    var message string = "AB"

    for _, value := range one_point{
        for _, rune_message := range message {
            if (value == strconv.QuoteRune(rune_message)) {
                fmt.Printf("%s equal %s \n", value,  strconv.QuoteRune(rune_message))
                fmt.Printf("%s in the array\n", strconv.QuoteRune(rune_message))
                fmt.Println("------------------------------")
            } else {
                fmt.Printf("%s not equal %s\n", value,  strconv.QuoteRune(rune_message))
                fmt.Printf("%s not in the array \n", strconv.QuoteRune(rune_message))
                fmt.Println("------------------------------")
            }
        }
    }
}

Here is the result:

A not equal 'A'
'A' not in the array 
------------------------------
A not equal 'B'
'B' not in the array
------------------------------
D not equal 'A'
'A' not in the array
------------------------------
D not equal 'B'
'B' not in the array
------------------------------
F not equal 'A'
'A' not in the array
------------------------------
F not equal 'B'
'B' not in the array
------------------------------

Visually, one string has ' while the other don't have.

I want to ask:

what is the difference between those 2 ?

How to fix my code to make it works ?

CodePudding user response:

You can see the reason from your output. A not equal 'A'.

strconv.QuoteRune is converting a rune to a string with ' quotation. It is comparing the "A" with "'A'", so it is not equal. If you would like to compare them in string, then you can do if value == string(rune_message).

TIPS:

  1. You should not use parenthesis for if condition.
  2. Use camel case instead of snake case.

CodePudding user response:

You are comparing a string containing a letter to a quoted string. You can simply do:

  one_point := []rune {'A', 'D', 'F'}
  ...
  for _, rune_message := range message {
     for _,value:=range one_point {
         if rune_message==value {
           ...
         }
      }
   }
  •  Tags:  
  • go
  • Related