Can i declare a const variable inside a struct in golang

8,752 views
Skip to first unread message

krma...@gmail.com

unread,
Mar 4, 2016, 5:40:09 PM3/4/16
to golang-nuts
Something like 


type A struct { 
Root string const 
Name string
}

Where Root is a constant for this struct which never changes .

Ian Lance Taylor

unread,
Mar 4, 2016, 5:44:54 PM3/4/16
to krma...@gmail.com, golang-nuts
No, sorry. I assume you want something like a field Root that is set
at initialization and never changed thereafter. Go doesn't support
anything like that. It would mean that the type had no useful zero
value (

Ian

Tyler Compton

unread,
Mar 4, 2016, 6:47:16 PM3/4/16
to golang-nuts
If you're curious about why this doesn't exist, take a look at this ticket:

milan...@gmail.com

unread,
Jun 26, 2017, 5:29:32 PM6/26/17
to golang-nuts
No, but you can do better thing! You can declare a method which returns a constant. E.g.:

func (a A) GetRoot()(string) {
return "MYroot"
}

Hope this helps, mate!

Dne pátek 4. března 2016 23:40:09 UTC+1 krma...@gmail.com napsal(a):
Reply all
Reply to author
Forward
0 new messages