Mr. Deepak Verma
Web Developer
Go Constants (स्थिरांक)

Learn Go Language by M-Learnify

Go Language

Go Constants (स्थिरांक)


Go Constants - हिंदी में समझाएँ

Go Constants (स्थायी मान)

यदि किसी वेरिएबल का मान स्थायी होना चाहिए और इसे बदला नहीं जा सकता, तो हम const कीवर्ड का उपयोग करते हैं।

Const कीवर्ड क्या है?

Const कीवर्ड वेरिएबल को "स्थायी" घोषित करता है, जिसका अर्थ है कि यह केवल पढ़ने योग्य (read-only) है और इसे बाद में बदला नहीं जा सकता।

सिंटैक्स

const CONSTNAME type = value

नोट: Constant का मान उसे घोषित करते समय ही दिया जाना चाहिए।

Constant घोषित करना

Example:

Example
package main
import ("fmt")

const PI = 3.14

func main() {
    fmt.Println(PI)
}

Constant के नियम

  • Constant के नाम वेरिएबल की तरह ही नियमों का पालन करते हैं।
  • Constant के नाम सामान्यतः बड़े अक्षरों में लिखे जाते हैं।
  • Constants को किसी फंक्शन के अंदर या बाहर दोनों जगह घोषित किया जा सकता है।

Constant के प्रकार

Constants के दो प्रकार होते हैं:

  1. Typed Constants (टाइप वाला)
  2. Untyped Constants (बिना टाइप वाला)

Typed Constants

Typed constants को एक निश्चित प्रकार के साथ घोषित किया जाता है।

Example
package main
import ("fmt")

const A int = 1

func main() {
    fmt.Println(A)
}

Untyped Constants

Untyped constants को बिना किसी प्रकार के घोषित किया जाता है।

Example
package main
import ("fmt")

const A = 1

func main() {
    fmt.Println(A)
}

नोट: इस मामले में compiler खुद प्रकार तय करता है।

Constants: अपरिवर्तनीय और केवल पढ़ने योग्य

एक बार constant घोषित करने के बाद इसे बदलना संभव नहीं है:

Example
package main
import ("fmt")

func main() {
    const A = 1
    A = 2
    fmt.Println(A)
}

Result:

Result
./prog.go:8:7: cannot assign to A

Multiple Constants Declaration

कई constants को एक ब्लॉक में घोषित किया जा सकता है:

Example
package main
import ("fmt")

const (
    A int = 1
    B = 3.14
    C = "Hi!"
)

func main() {
    fmt.Println(A)
    fmt.Println(B)
    fmt.Println(C)
}
← Back to Courses
Course Lessons