Programmazione in Golang: l'uso dei vettori (array , variabili indicizzate) e delle matrici (matrix - array bidimensionali) in Golang
Lezione universitaria su Golang - esame "Programmazione"
Array in Go
Nel linguaggio di programmazione Golang o Go i vettori (array o variabili indicizzate) sono molto simili ad altri linguaggi di programmazione. Nel programma, a volte è necessario memorizzare una raccolta di dati dello stesso tipo, come un elenco di voti degli studenti. Tale tipo di raccolta è memorizzata in un programma usando un array. Un array è una sequenza a lunghezza fissa che viene utilizzata per memorizzare elementi omogenei nella memoria. A causa della loro dimensione a lunghezza fissa non sono molto utilizzati, si preferisce usare i vettori dinamici Slice in Go.
In un array, è consentito memorizzare zero o più di zero elementi al suo interno. Gli elementi dell'array vengono indicizzati utilizzando l'operatore indice [] con la loro posizione in base zero, significa che l'indice del primo elemento è array [0] e l'indice dell'ultimo elemento è array [len (array) -1] .
Creazione e accesso a una matrice
Nella lingua Go, le matrici vengono create in due modi diversi:
Utilizzo della parola chiave var : nella lingua Go, viene creata una matrice utilizzando la parola chiave var di un determinato tipo con nome, dimensione ed elementi.
Sintassi: Var array_name [lunghezza] Tipo o var array_name [lunghezza] Digitare {item1, item2, item3, ... itemN}
Punti importanti:
Nella lingua Go, gli array sono mutabili, in modo da poter utilizzare la sintassi dell'array [indice] sul lato sinistro dell'assegnazione per impostare gli elementi dell'array in corrispondenza dell'indice specificato.Var array_name [index] = element
È possibile accedere agli elementi dell'array utilizzando il valore dell'indice o utilizzando il ciclo for.
Nel linguaggio Go, il tipo di array è monodimensionale.
La lunghezza dell'array è fissa e immutabile.
È consentito memorizzare elementi duplicati in un array.
Esempio:
// Go program to illustrate how to
// create an array using the var keyword
// and accessing the elements of the
// array using their index value
package main
import "fmt"
func main() {
// Creating an array of string type
// Using var keyword
var myarr[3]string
// Elements are assigned using index
myarr[0] = "GFG"
myarr[1] = "GeeksforGeeks"
myarr[2] = "Geek"
// Accessing the elements of the array
// Using index value
fmt.Println("Elements of Array:")
fmt.Println("Element 1: ", myarr[0])
fmt.Println("Element 2: ", myarr[1])
fmt.Println("Element 3: ", myarr[2])
}
Produzione: Elements of Array: Elemento 1: GFG Elemento 2: GeeksforGeeks Elemento 3: Geek
Utilizzo della dichiarazione abbreviata: nella lingua Go, gli array possono anche dichiarare utilizzando la dichiarazione abbreviata. È più flessibile della suddetta dichiarazione.
Sintassi: array_name: = [lunghezza] Digita {item1, item2, item3, ... itemN}
Esempio:
// Go program to illustrate how to create
// an array using shorthand declaration
// and accessing the elements of the
// array using for loop
package main
import "fmt"
func main() {
// Shorthand declaration of array
arr:= [4]string{"geek", "gfg", "Geeks1231", "GeeksforGeeks"}
// Accessing the elements of
// the array Using for loop
fmt.Println("Elements of the array:")
for i:= 0; i < 3; i++{
fmt.Println(arr[i])
}
}
Produzione: Elementi dell'array: disadattato GFG Geeks1231
Matrice multidimensionale
Come già sappiamo che le matrici sono 1-D ma ti è permesso creare una matrice multidimensionale. Le matrici multidimensionali sono le matrici di matrici dello stesso tipo . In lingua Go, è possibile creare un array multidimensionale utilizzando la sintassi seguente:
ARRAY_NAME [Lunghezza1] [Lunghezza2] .. [LengthN] Tipo
È possibile creare un array multidimensionale utilizzando la parola chiave Var o la dichiarazione abbreviata, come mostrato nell'esempio seguente.
Nota: nell'array multidimensionale, se una cella non è inizializzata con un certo valore dall'utente, verrà automaticamente inizializzata con zero dal compilatore. Non esiste un concetto non inizializzato nel Golang.
Esempio:
// Go program to illustrate the
// concept of multi-dimension array
package main
import "fmt"
func main() {
// Creating and initializing
// 2-dimensional array
// Using shorthand declaration
// Here the (,) Comma is necessary
arr:= [3][3]string{{"C#", "C", "Python"},
{"Java", "Scala", "Perl"},
{"C++", "Go", "HTML"},}
// Accessing the values of the
// array Using for loop
fmt.Println("Elements of Array 1")
for x:= 0; x < 3; x++{
for y:= 0; y < 3; y++{
fmt.Println(arr[x][y])
}
}
// Creating a 2-dimensional
// array using var keyword
// and initializing a multi
// -dimensional array using index
var arr1 [2][2] int
arr1[0][0] = 100
arr1[0][1] = 200
arr1[1][0] = 300
arr1[1][1] = 400
// Accessing the values of the array
fmt.Println("Elements of array 2")
for p:= 0; p<2; p++{
for q:= 0; q<2; q++{
fmt.Println(arr1[p][q])
}
}
}
Produzione:Elements of Array 1 C # C Pitone Giava Scala Perl C ++ Partire HTML Elementi dell'array 2 100 200 300 400
Osservazioni importanti sull'array
In un array, se un array non viene inizializzato esplicitamente, il valore predefinito di questo array è 0.
Esempio:
// Go program to illustrate an array
package main
import "fmt"
func main() {
// Creating an array of int type
// which stores, two elements
// Here, we do not initialize the
// array so the value of the array
// is zero
var myarr[2]int
fmt.Println("Elements of the Array :", myarr)
}
Produzione: Elements of the Array: [0 0]
In un array, puoi trovare la lunghezza dell'array usando il metodo len () come mostrato di seguito:
Esempio:
// Go program to illustrate how to find
// the length of the array
package main
import "fmt"
func main() {
// Creating array
// Using shorthand declaration
arr1:= [3]int{9,7,6}
arr2:= [...]int{9,7,6,4,5,3,2,4}
arr3:= [3]int{9,3,5}
// Finding the length of the
// array using len method
fmt.Println("Length of the array 1 is:", len(arr1))
fmt.Println("Length of the array 2 is:", len(arr2))
fmt.Println("Length of the array 3 is:", len(arr3))
}
Produzione: La lunghezza dell'array 1 è: 3 La lunghezza dell'array 2 è: 8 La lunghezza dell'array 3 è: 3
In una matrice, se i puntini di sospensione '' ... '' diventano visibili nel punto di lunghezza, la lunghezza della matrice viene determinata dagli elementi inizializzati. Come mostrato nell'esempio seguente:
Esempio:
// Go program to illustrate the
// concept of ellipsis in an array
package main
import "fmt"
func main() {
// Creating an array whose size is determined
// by the number of elements present in it
// Using ellipsis
myarray:= [...]string{"GFG", "gfg", "geeks",
"GeeksforGeeks", "GEEK"}
fmt.Println("Elements of the array: ", myarray)
// Length of the array
// is determine by
// Using len() method
fmt.Println("Length of the array is:", len(myarray))
}
Produzione:
Elementi dell'array: [GFG gfg geeks GeeksforGeeks GEEK] La lunghezza dell'array è: 5
In un array, è possibile eseguire l'iterazione nell'intervallo degli elementi dell'array . Come mostrato nell'esempio seguente:
Esempio:
// Go program to illustrate
// how to iterate the array
package main
import "fmt"
func main() {
// Creating an array whose size
// is represented by the ellipsis
myarray:= [...]int{29, 79, 49, 39, 20, 49, 48, 49}
// Iterate array using for loop
for x:=0; x < len(myarray); x++{
fmt.Printf("%d\n", myarray[x])
}
}
Produzione: 29 79 49 39 20 49 48 49
Nella lingua Go, un array è di tipo valore non di tipo di riferimento . Pertanto, quando l'array viene assegnato a una nuova variabile, le modifiche apportate alla nuova variabile non influiscono sull'array originale. Come mostrato nell'esempio seguente:
Esempio:
// Go program to illustrate value type array
package main
import "fmt"
func main() {
// Creating an array whose size
// is represented by the ellipsis
my_array:= [...]int{100, 200, 300, 400, 500}
fmt.Println("Original array(Before):", my_array)
// Creating a new variable
// and initialize with my_array
new_array := my_array
fmt.Println("New array(before):", new_array)
// Change the value at index 0 to 500
new_array[0] = 500
fmt.Println("New array(After):", new_array)
fmt.Println("Original array(After):", my_array)
}
Produzione: Matrice originale (prima): [100 200 300 400 500] Nuovo array (prima): [100 200 300 400 500] Nuovo array (dopo): [500 200 300 400 500] Matrice originale (dopo): [100 200 300 400 500]
In un array, se il tipo di elemento dell'array è comparabile, anche il tipo di array è comparabile. Quindi possiamo confrontare direttamente due array usando l'operatore == . Come mostrato nell'esempio seguente:
Esempio:
// Go program to illustrate
// how to compare two arrays
package main
import "fmt"
func main() {
// Arrays
arr1:= [3]int{9,7,6}
arr2:= [...]int{9,7,6}
arr3:= [3]int{9,5,3}
// Comparing arrays using == operator
fmt.Println(arr1==arr2)
fmt.Println(arr2==arr3)
fmt.Println(arr1==arr3)
// This will give and error because the
// type of arr1 and arr4 is a mismatch
/*
arr4:= [4]int{9,7,6}
fmt.Println(arr1==arr4)
*/
}
Produzione: vero falso falso
fonte: https://www.geeksforgeeks.org/arrays-in-go/
Commenti
Posta un commento