In JavaScript I can store the values of array into variables like this:
[a, b, c] = [1, 2, 3]
I created a variable function( it return a map with the same number of arguments), I would like to know if Go has a shortcut like JavaScript
In JavaScript I can store the values of array into variables like this:
[a, b, c] = [1, 2, 3]
I created a variable function( it return a map with the same number of arguments), I would like to know if Go has a shortcut like JavaScript
Based on the suggestion from comments ,I created a small example for your scenario:
package main
import (
"fmt"
)
func main() {
myArray := []int{1, 2, 3}
fmt.Println(myArray)
a, b, c := myArray[0], myArray[1], myArray[2]
fmt.Println(a, b, c)
}
Output:
[1 2 3]
1 2 3
Javascript's destructuring assignment syntax is not available in Go, however Go's syntax is sometimes concise too, depending what your input looks like.
Declaring and initializing several variables in a single LOC is straightforward, and it works even with variables of different types:
a, b, c := 42, "hello", 5.0
You can assign values to existing variables as well:
a, b, c = 42, "hello", 5.0
If your input data is a slice s, then per @Gopher's answer the code will look like:
a, b, c := s[0], s[1], s[2]