The keyword for Golang Constant is const , Once the Constant variable declared it cannot be modified.
Same as Var keyword, we can declare constant as two types.
1. Typed -- const a string = "abc"
2. Untyped -- const a ="abc"
Same as Var keyword, we can declare constant as two types.
1. Typed -- const a string = "abc"
2. Untyped -- const a ="abc"
Example for using Golang Constants:
package main
import "fmt"
// declaring Multiple variables
const (
a = 1
b = "hi"
c = 1.1
)
func main() {
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
}
Output:
1
hi
1.1
Another Example:
package main
import "fmt"
func main() {
const a = "Hello"
a = "Hi"
fmt.Println(a)
}
Output:./prog.go:7:2: cannot assign to a (untyped string constant "Hello") Go build failed.
Another Example:
package main
import "fmt"
func main() {
// declare and initialize a constant string
const s string = "MY_CONST"
// define a custom string type - str
type str string
// storing the const variable in a new variable is allowed
var newString string = s
// storing the const variable in a new custom type variable is allowed
var customString str = s
// But storing the custom type variable in the normal string variable is not allowed
newString = customString
fmt.Println(newString)
fmt.Println(customString)
}
Output:
./prog.go:17:25: cannot use s (constant "MY_CONST" of type string) as str value in variable declaration
./prog.go:20:14: cannot use customString (variable of type str) as string value in assignment
Go build failed.
Comments
Post a Comment