[go-nuts] const in struct

5,489 views
Skip to first unread message

Newbie

unread,
Apr 18, 2010, 8:50:55 AM4/18/10
to golang-nuts
Hi all,

is it possible to declare a "const" in struct? Something simmilar to

type my_struct struct {
value string const // <-- doesn't work
}

Thanks


--
Subscription settings: http://groups.google.com/group/golang-nuts/subscribe?hl=en

befelemepeseveze

unread,
Apr 18, 2010, 10:21:25 AM4/18/10
to golang-nuts
On 18 dub, 14:50, Newbie <postmasch...@gmail.com> wrote:

> is it possible to declare a "const" in struct? Something simmilar to
>
> type my_struct struct {
>     value    string const        // <-- doesn't work
>
> }

No.

http://golang.org/doc/go_spec.html#Struct_types

peterGo

unread,
Apr 18, 2010, 11:28:57 AM4/18/10
to golang-nuts
Newbie,

There are boolean constants, integer constants, floating-point
constants, complex constants, and string constants.
http://golang.org/doc/go_spec.html#Constants

However you can't add const to the type system, and that is not likely
to change.
http://groups.google.com/group/golang-nuts/msg/7d7ec2854db125f2

Peter

chris dollin

unread,
Apr 18, 2010, 11:36:17 AM4/18/10
to Newbie, golang-nuts
On 18 April 2010 13:50, Newbie <postma...@gmail.com> wrote:
Hi all,

is it possible to declare a "const" in struct? Something simmilar to

type my_struct struct {
   value    string const        // <-- doesn't work
}

If you don't export the name, then outside the declaring
package you can't see it, let alone change it.

Disadvantage: you also then can't assign the struct
at all without going through some method/function.

Would that do?

--
Chris "allusive" Dollin

travelnor...@gmail.com

unread,
Mar 23, 2016, 8:50:42 PM3/23/16
to golang-nuts, postma...@gmail.com
In addition to the above, the work around is quite simple if can use a method instead of a field:

type my_struct struct {}

func (m *my_struct) ConstantString() string {
    return "always return this"
Reply all
Reply to author
Forward
0 new messages