结构声明中的文字值

Say we have a struct like so:

type Foo struct {
  one string
  two int
}

is it possible to declare literal values for this, something like:

type Foo struct {
  one "foobar"
  two int
}

or

type Foo struct {
  one string
  two 5678
}

basically for some objects we might have a hardcoded value for a field.

No, Go does not support literal types (a la TypeScript). Moreover, it actually can't, because of zero values.

Every type has a zero value which always exists and is always assignable to it. When variables of a type are declared, they are implicitly assigned to their type's zero value.

  • For integer (int, uint, int32, uint32, int64, uin64) or float (float32, float64) or complex (complex64 or complex128) types, this is just 0 (0.0 respectively).

  • For string types, this is the empty string "".

  • For slices, maps, pointers, channels, and interfaces, the zero value is nil.

  • For arrays (not slices: arrays are value-types with statically-known length); their zero value is just the zero value of the element type repeated to fill every slot

  • The zero value of a struct type is a struct all of whose fields are zero values

In any case, because it is always possible for any type to have a zero value, it would be incompatible to create a type which only allows for any particular non-zero value.

The best a literal type "foo" could possibly represent is that the value is either "foo" or the zero value "" (and no, Go doesn't support this anyway).

The closest you'll be able to do is a constant declaration, or a receiver function that just-so-happens to return a fixed value instead of an actual field.

Go is statically typed language, meaning every variable need to be declared with specific data type.

Setting default value for each fields inside a struct on declaration is not possible in Go. it's not supported.

But maybe you can do something like this.

type Foo struct {
    one string
    two int
}

func NewFoo() *Foo {
    foo := new(Foo)
    foo.one = "default value for one"
    foo.two = 2
    return foo
}

func main() {
    objectWithDefaultValueForItsField := NewFoo()
}

What I did is basically just created a function with name is
New<struct name>(). This function returns a new object with default value for each of the fields defined.


Notable exception, for object that created from anonymous struct, the default value of the fields can be specified on declaration. i.e.

obj := struct {
    one string
    two int
}{
    "default value for one",
    2,
}