Operador de declaración de variable breve (:=) en Go

El operador de declaración de variable corta (:=) en Golang se usa para crear las variables que tienen un nombre propio y un valor inicial. El objetivo principal de usar este operador para declarar e inicializar las variables locales dentro de las funciones y reducir el alcance de las variables. El tipo de la variable está determinado por el tipo de la expresión. La palabra clave var también se usa para crear las variables de un tipo específico. Entonces puede decir que hay dos formas de crear las variables en Golang de la siguiente manera:

  • Usando la palabra clave var
  • Usando el operador de declaración de variable corta (:=)

En este artículo, solo discutiremos el operador de declaración de variable corta. Para conocer la palabra clave var, puede consultar la palabra clave var en Go . También puede leer la diferencia entre la palabra clave var y el operador de declaración de variable corta para tener una idea adecuada del uso de ambos.

Sintaxis del uso del operador de declaración de variable corta: 

variable_name := expression or value

Aquí, debe inicializar la variable justo después de la declaración. Pero al usar la palabra clave var puede evitar la inicialización en el momento de la declaración. No es necesario mencionar el tipo de variable . La expresión o valor del lado derecho se utiliza para evaluar el tipo de variable.

Ejemplo: aquí declaramos las variables usando un operador de declaración corto y no especificamos el tipo de variable. El tipo de la variable está determinado por el tipo de la expresión en el lado derecho del operador  := .

Go

// Go program to illustrate the use
// of := (short declaration
// operator)
package main
 
import "fmt"
 
func main() {
 
    // declaring and initializing the variable 
    a := 30
 
    // taking a string variable
    Language: = "Go Programming"
 
    fmt.Println("The Value of a is: ", a)
    fmt.Println("The Value of Language is: ", Language)
   
}

Producción:

The Value of a is:  30
The Value of Language is:  Go Programming

Declarar múltiples variables utilizando el operador de declaración breve (:=)

El operador de declaración corta también se puede usar para declarar múltiples variables del mismo tipo o diferentes tipos en la declaración única. El tipo de estas variables se evalúa mediante la expresión del lado derecho del operador  := .

Ejemplo: 

Go

// Go program to illustrate how to use := short
// declaration operator to declare multiple
// variables into a single declaration statement
package main
  
import "fmt"
 
func main() {
 
// multiple variables of same type(int)
geek1, geek2, geek3 := 117, 7834, 5685
 
// multiple variables of different types
geek4, geek5, geek6 := "GFG", 859.24, 1234
 
// Display the value and
// type of the variables
fmt.Printf("The value of geek1 is : %d\n", geek1)
fmt.Printf("The type of geek1 is : %T\n", geek1)
 
fmt.Printf("\nThe value of geek2 is : %d\n", geek2)
fmt.Printf("The type of geek2 is : %T\n", geek2)
 
fmt.Printf("\nThe value of geek3 is : %d\n", geek3)
fmt.Printf("The type of geek3 is : %T\n", geek3)
 
fmt.Printf("\nThe value of geek4 is : %s\n", geek4)
fmt.Printf("The type of geek4 is : %T\n", geek4)
 
 
fmt.Printf("\nThe value of geek5 is : %f\n", geek5)
fmt.Printf("The type of geek5 is : %T\n", geek5)
 
fmt.Printf("\nThe value of geek6 is : %d\n", geek6)
fmt.Printf("The type of geek6 is : %T\n", geek6)
  
}

Producción:

The value of geek1 is : 117
The type of geek1 is : int

The value of geek2 is : 7834
The type of geek2 is : int

The value of geek3 is : 5685
The type of geek3 is : int

The value of geek4 is : GFG
The type of geek4 is : string

The value of geek5 is : 859.240000
The type of geek5 is : float64

The value of geek6 is : 1234
The type of geek6 is : int

Puntos importantes: 

  • El operador de declaración corta se puede usar cuando al menos una de las variables en el lado izquierdo del operador := se declara recientemente. Un operador de declaración de variable breve se comporta como una asignación para aquellas variables que ya están declaradas en el mismo bloque léxico. Para tener una mejor idea sobre este concepto, tomemos un ejemplo.
    Ejemplo 1: El siguiente programa dará un error ya que no hay nuevas variables en el lado izquierdo del operador := .

Go

// Go program to illustrate the concept
// of short variable declaration
package main
 
import "fmt"
 
func main() { 
 
    // taking two variables
    p, q := 100, 200
 
    fmt.Println("Value of p ", p, "Value of q ", q)
 
    // this will give an error as
    // there are no new variable
    // on the left-hand side of :=
    p, q := 500, 600
    
    fmt.Println("Value of p ", p, "Value of q ", q)
}

Error:

./prog.go:17:10: no hay nuevas variables en el lado izquierdo de := 
 

Ejemplo 2: en el siguiente programa, puede ver que la línea de código geek3, geek2 := 456, 200 funcionará bien sin ningún error ya que hay al menos una nueva variable, es decir, geek3 en el lado izquierdo del operador := .

Go

// Go program to show how to use
// short variable declaration operator
package main
 
import "fmt"
 
func main() {
 
// Here, short variable declaration acts
// as an assignment for geek1 variable
// because same variable present in the same block
// so the value of geek2 is changed from 100 to 200
geek1, geek2 := 78, 100
 
// here, := is used as an assignment for geek2
// as it is already declared. Also, this line
// will work fine as geek3 is newly created
// variable
geek3, geek2 := 456, 200
 
// If you try to run the commented lines,
// then compiler will gives error because
// these variables are already defined
// geek1, geek2 := 745, 956
// geek3 := 150
 
// Display the values of the variables
fmt.Printf("The value of geek1 and geek2 is : %d %d\n", geek1, geek2)
                                             
fmt.Printf("The value of geek3 and geek2 is : %d %d\n", geek3, geek2)
}

Producción:

The value of geek1 and geek2 is : 78 200
The value of geek3 and geek2 is : 456 200
  • Go es un lenguaje fuertemente tipado ya que no puede asignar un valor de otro tipo a la variable declarada. 
      Ejemplo:

Go

// Go program to show how to use
// short variable declaration operator
package main
 
import "fmt"
 
func main() {
 
    // taking a variable of int type
    z := 50
     
    fmt.Printf("Value of z is %d", z)
     
    // reassigning the value of string type
    // it will give an error
    z := "Golang"
}

Error:

./prog.go:16:4: no hay nuevas variables en el lado izquierdo de := 
./prog.go:16:7: no se puede usar «Golang» (tipo string) como tipo int en la asignación 
 

  • En una declaración de variable corta, se permite inicializar un conjunto de variables mediante la función de llamada que devuelve múltiples valores. O puede decir que a las variables también se les pueden asignar valores que se evalúan durante el tiempo de ejecución. 
    Ejemplo:
// Here, math.Max function return 
// the maximum number in i variable
i := math.Max(x, y)

¿Variables locales o variables globales?

Con la ayuda del operador de declaración de variable breve (:=) , solo puede declarar la variable local que solo tiene alcance a nivel de bloque. Generalmente, las variables locales se declaran dentro del bloque de funciones. Si intenta declarar las variables globales usando el operador de declaración corto, obtendrá un error.

Ejemplo 1: 

Go

// Go program to show the use of := operator
// to declare local variables
package main
   
import "fmt"
   
// using var keyword to declare 
// and initialize the variable
// it is package or you can say 
// global level scope
var geek1 = 900
   
// using short variable declaration
// it will give an error
geek2 := 200
   
func main() {
   
// accessing geek1 inside the function
fmt.Println(geek1)
  
// accessing geek2 inside the function
fmt.Println(geek2)
       
}

Error:

./prog.go:15:1: error de sintaxis: declaración sin declaración fuera del cuerpo de la función 
 

Ejemplo 2:

Go

// Go program to show the use of := operator
// to declare local variables
package main
   
import "fmt"
   
// using var keyword to declare 
// and initialize the variable
// it is package or you can say 
// global level scope
var geek1 = 900
 
   
func main() {
 
// using short variable declaration
// inside the main function
// it has local scope i.e. can't
// accessed outside the main function
geek2 := 200
   
// accessing geek1 inside the function
fmt.Println(geek1)
  
// accessing geek2 inside the function
fmt.Println(geek2)
       
}

Producción: 

900
200

Publicación traducida automáticamente

Artículo escrito por Anshul_Aggarwal y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *