Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

210
Vistas
How do I get the switch statement to work when there is an error in switch case

based on user input from command line, switch case returns rating for an integer. Since command line arguments are of type string, I first convert it to int and then use it in switch.

package main

import (
  "fmt"
  "os"
  "reflect"
  "strconv"
)

func main() {
 rating, _ := strconv.Atoi(os.Args[1])
 fmt.Println(reflect.TypeOf(rating))
 switch rating {
  case rating >= 2100:
    fmt.Println("grand master")
  case rating >= 1900:
    fmt.Println("candidate master")
  case rating >= 1600:
    fmt.Println("expert")
  case rating >= 1400:
    fmt.Println("pupil")
  case rating < 1400:
    fmt.Println("newbie")
  }

}

Now there is error on rating >= 2100, for all comparisons rather. It goes as follows:

cannot convert rating >= 2100 (untyped bool value) to intcompilerInvalidUntypedConversion

Not able to understand how to resolve this.

Please help!

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

If you use a switch expression, you have to use case expressions where they are comparable. Spec: Switch statements:

For each (possibly converted) case expression x and the value t of the switch expression, x == t must be a valid comparison.

That is, if you use switch rating { ... }, then you only need to specify the integer values, e.g. 2100, and not a comparison like rating >= 2100.

Obviously you don't want single values but ranges, so omit the switch expression:

switch {
case rating >= 2100:
    fmt.Println("grand master")
case rating >= 1900:
    fmt.Println("candidate master")
case rating >= 1600:
    fmt.Println("expert")
case rating >= 1400:
    fmt.Println("pupil")
case rating < 1400:
    fmt.Println("newbie")
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda