Arrays क्या हैं
var name [size]type
name := [size]type{v1, v2, v3}
name := [...]type{v1, v2, v3}
Declaring a Fixed-Size Array
एक array type उसकी length शामिल करता है, जैसे बिल्कुल पांच integers वाले array के लिए [5]int। एक बार declared होने पर, इसका size कभी नहीं बदल सकता -- यह dynamically sized languages में arrays/lists से मूल रूप से अलग है।
उदाहरण: Declaring a Fixed-Size Array
// Every Go file belongs to a package; main builds an executable
package main
// Import the fmt package
import "fmt"
// main is where the program starts running
func main() {
// Declare scores with the zero value of its type
var scores [5]int
scores[0] = 90
scores[1] = 85
// Print the values followed by a newline
fmt.Println(scores)
}
Login to try C/C++/Java/PHP code in the editor
Array Literals
एक array को एक literal का उपयोग करके एक step में declare और भरा जा सकता है, और [...] syntax Go को आपके हाथ से length specify करने के बजाय elements को अपने आप गिनने के लिए कहता है।
उदाहरण: Array Literals
// Every Go file belongs to a package; main builds an executable
package main
// Import the fmt package
import "fmt"
// main is where the program starts running
func main() {
// Short declaration: create primes and infer the type
primes := [...]int{2, 3, 5, 7, 11}
// Print the values followed by a newline
fmt.Println(primes, "length:", len(primes))
}
Login to try C/C++/Java/PHP code in the editor
Arrays Are Copied by Value
Slices के विपरीत, किसी Go array को एक नए variable को assign करना (या इसे किसी function को पास करना) हर element को एक बिल्कुल नई array में copy कर देता है -- copy को modify करना कभी original को प्रभावित नहीं करता।
उदाहरण: Arrays Are Copied by Value
// Every Go file belongs to a package; main builds an executable
package main
// Import the fmt package
import "fmt"
// main is where the program starts running
func main() {
// Short declaration: create original and infer the type
original := [3]int{1, 2, 3}
// Short declaration: create copy and infer the type
copy := original
copy[0] = 99
// Print the values followed by a newline
fmt.Println("original:", original)
// Print the values followed by a newline
fmt.Println("copy:", copy)
}
Login to try C/C++/Java/PHP code in the editor
- यह मान लेना कि कोई array बनने के बाद बढ़ या सिकुड़ सकता है -- Go arrays की एक fixed length उनके type में बेक होती है।
- यह भूल जाना कि किसी array को किसी दूसरे variable को assign करना पूरी array को copy करता है, उसी data के reference को नहीं।
- Arrays को slices के साथ confuse करना और [5]int और []int को interchangeably उपयोग करना -- ये अलग, असंगत types हैं।
- एक Go array की एक fixed length होती है जो इसके type का हिस्सा है, जैसे [5]int।
- Arrays value types हैं -- किसी एक को assign या पास करना इसके सभी elements copy करता है।
- Array length को [...]Type{...} literal syntax से infer किया जा सकता है।
- Practice में, slices (arrays के ऊपर बने) raw arrays से कहीं ज़्यादा उपयोग होते हैं।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: