On Tue, May 28, 2019 at 11:04 AM Trig <[email protected]> wrote: > Whoops... forgot to add the top line to the code syntax. I really wish > you could edit existing posts in this group. > > On Tuesday, May 28, 2019 at 10:03:05 AM UTC-5, Trig wrote: >> >> package main >> >> import "fmt" >> >> const ( >> ExposedConstant = "1" // exposed outside of package >> internalConstant = "2" // for use anywhere in package only >> ) >> >> func main() { >> const functionConstant = "3" // usable anywhere in main func >> >> fmt.Println(ExposedConstant, internalConstant, functionConstant) >> } >> >> >> https://golang.org/ref/spec#Constants Note that the const keyword can only be used with primitive types. For more complicated values, I tend to use functions/methods. (the GC compiler's inliner is smart enough to inline a function call to a function with exactly one return statement containing a small struct literal)
e.g. https://play.golang.org/p/AaLXcZ-CYEY package main > import "fmt" > // Foo is a structtype Foo struct { > A int > B string > } > // DefaultFoo returns a useful default structfunc DefaultFoo() Foo { > return Foo{ > A: 1, > B: "abcd", > } > } > // Bim does somethingfunc Bim() { > fmt.Printf("%+v\n", DefaultFoo()) > } > > >> On Tuesday, May 28, 2019 at 7:12:06 AM UTC-5, Ashutosh Baghel wrote: >>> >>> Hello folks, >>> >>> I want to declare a few variables constant. But I guess there is nothing >>> as "Constant" type in GoLang. How do I achieve this in GoLang? >>> >> For those with an interest in the inlining behavior, Matt Godbolt's Compiler Explorer supports Go. Here's a small modification of the example above (mostly just moved it out of the main package and removed the imports to reduce the amount of code generated): https://go.godbolt.org/z/izOJVU -- > You received this message because you are subscribed to the Google Groups > "golang-nuts" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to [email protected]. > To view this discussion on the web visit > https://groups.google.com/d/msgid/golang-nuts/c9b3b7df-b2da-42ce-bd9e-44ee1eb589ba%40googlegroups.com > <https://groups.google.com/d/msgid/golang-nuts/c9b3b7df-b2da-42ce-bd9e-44ee1eb589ba%40googlegroups.com?utm_medium=email&utm_source=footer> > . > For more options, visit https://groups.google.com/d/optout. > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CANrC0Bj_iiNPTxVzXF%2By4r-H4DXa7_HU%2BjF9%3D1jk7juvZ34zSA%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
