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

199
Vistas
Changing variable value inside golang switch statement
package main

import "fmt"

func main() {
    var i int = 10
    switch true {
    case i < 20:
        fmt.Printf("%v is less than 20\n", i)
        i = 100
        fallthrough
    case i < 19:
        fmt.Printf("%v is less than 19\n", i)
        fallthrough
    case i < 18:
        fmt.Printf("%v is less than 18\n", i)
        fallthrough
    case i > 50:
        fmt.Printf("%v is greater than 50\n", i)
        fallthrough
    case i < 19:
        fmt.Printf("%v is less than 19\n", i)
        fallthrough
    case i == 100:
        fmt.Printf("%v is equal to 100\n", i)
        fallthrough
    case i < 17:
        fmt.Printf("%v is less than 17\n", i)
    }
}

Output:

10 is less than 20
100 is less than 19
100 is less than 18
100 is greater than 50
100 is less than 19
100 is equal to 100
100 is less than 17

Is this expected behavior?

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

0

The fallthrough statement transfers control to the first statement of the next case block.

The fallthrough statement does not mean to continue evaluating the expression of the next case, but to unconditionally start executing the next case block.

Quoting from fallthrough statement doc:

A "fallthrough" statement transfers control to the first statement of the next case clause in an expression "switch" statement.

Quoting from switch statement doc:

In a case or default clause, the last non-empty statement may be a (possibly labeled) "fallthrough" statement to indicate that control should flow from the end of this clause to the first statement of the next clause. Otherwise control flows to the end of the "switch" statement.

over 4 years ago · Santiago Trujillo Denunciar

0

Yes it is, as pointed by icza.

If you don't want to fall under every case block after first, remove fallthrough lines (it's like you wouldn't have put a break line at the end of each C/C++ case block.

And, as you expect in comments, the evaluation is done when switch() is reached, after that it doesn't matter if you change i value, it won't be evaluated again on each case block.

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