ADVERTISEMENT
ADVERTISEMENT

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 »

ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.