In some languages, such as Java and C++, constants can be created and then assigned their value during the constructor (and then not changed after that). Is there any way to do this in Golang so that a constant whose value won't be known until runtime can be created? Thanks in advance!
In Golang, all constants are untyped unless they are explicitly given a type at declaration. Untyped constants allow for flexibility. They can be assigned to any variable of compatible type or mixed into mathematical operations.
In Go, const is a keyword introducing a name for a scalar value such as 2 or 3.14159 or "scrumptious" . Such values, named or otherwise, are called constants in Go. Constants can also be created by expressions built from constants, such as 2+3 or 2+3i or math. Pi/2 or ("go"+"pher") .
An untyped constant has a default type which is the type to which the constant is implicitly converted in contexts where a typed value is required. For example default type for integer constant is int or it's float64 for floating-point number. In program V variable c is being set to untyped constant expression 1 .
You can not create constants of maps, arrays and it is written in effective go: Constants in Go are just that—constant. They are created at compile time, even when defined as locals in functions, and can only be numbers, characters (runes), strings or booleans.
Constants in go are set at compile time, see the relevant section in the docs here: https://golang.org/doc/effective_go.html#constants
Constants in Go are just that—constant. They are created at compile time, even when defined as locals in functions, and can only be numbers, characters (runes), strings or booleans. Because of the compile-time restriction, the expressions that define them must be constant expressions, evaluatable by the compiler. For instance, 1<<3 is a constant expression, while math.Sin(math.Pi/4) is not because the function call to math.Sin needs to happen at run time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With