×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Can we declare multiple variables at once in Go?

Golang | Declaring multiple variables: In this tutorial, we will learn how we can declare and assign multiple variables at once?
Submitted by IncludeHelp, on October 03, 2021

Yes, we can declare multiple variables at once in Go.

Declaring multiple variables at once

Use the following syntax to declare multiple variables of the same type at once,

var variable1, variable2, ... type

Assigning values to multiple variables at once

variable1, variable2, ... = value1, value2, ...

Example 1:

package main

import "fmt"

func main() {
	// Declaring variables together
	var a, b, c string

	// Assigning values together
	a, b, c = "Hello", "World", "Golang"

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

Output:

string, "Hello"
string, "World"
string, "Golang"

Example 2:

package main

import "fmt"

func main() {
	// Declaring variables together
	var a, b, c int

	// Assigning the same values together
	a, b, c = 10, 10, 10

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

	// Updating the value of b
	b = 20
	fmt.Printf("After updating b: %T, %d\n", b, b)
}

Output:

int, 10
int, 10
int, 10
After updating b: int, 20

Golang FAQ »



Comments and Discussions!

Load comments ↻





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