Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Runtime Const in Golang

Tags:

constants

go

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!

like image 960
Ryan Avatar asked Jan 27 '16 00:01

Ryan


People also ask

Does Golang have const?

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.

How do you use const in Go?

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") .

What is untyped constant?

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 .

How do I create a constant map in Golang?

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.


1 Answers

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.

like image 80
ctcherry Avatar answered Sep 29 '22 23:09

ctcherry