How to declare and assign multiple variables using short variable declaration in Golang?

Short variable declaration in Golang: Lean, how to declare and assign multiple variables in a single declaration?
Submitted by IncludeHelp, on October 19, 2021

If we have a list of variables of the same types or the different types, we can declare and assign them by using the short variable declaration by using the following syntax,

variable1, variable2, variable3, ... := value1, value2, value3, ...

Example 1:

package main

import (
	"fmt"
)

func main() {
	// Declaraing and assigning multiple
	// variables
	a, b, c := 10, 20, 30

	// Printing the types and values
	fmt.Printf("a: %T, %d\n", a, a)
	fmt.Printf("b: %T, %d\n", b, b)
	fmt.Printf("c: %T, %d\n", c, c)
}

Output:

a: int, 10
b: int, 20
c: int, 30

Example 2:

package main

import (
	"fmt"
)

func main() {
	// Declaraing and assigning multiple
	// variables
	name, age, roll_no, perc := "Alvin", 21, 101, 84.9

	// Printing the types and values
	fmt.Printf("name: %T, %s\n", name, name)
	fmt.Printf("age: %T, %d\n", age, age)
	fmt.Printf("roll_no: %T, %d\n", roll_no, roll_no)
	fmt.Printf("perc: %T, %f\n", perc, perc)
}

Output:

name: string, Alvin
age: int, 21
roll_no: int, 101
perc: float64, 84.900000

Golang FAQ »



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.