Golang中的结构声明[关闭]

Given Go is largely based on C, and structs in that language are defined like this:

struct Person{...}

Why do we have the extra word in Go?

type Person struct{...}

Why do we need to mention both type and struct? Seems a little verbose.

All top-level statements in Go begin with a keyword indicating the type of declaration: package, import, type, var, const, or func, per the Go specification. As to why those decisions were made, you would need to ask those who made them, i.e. the Go maintainers.

One word: consistency.

The type keyword is used in all type definitions. Note that a defined type's underlying type needs not be a struct; for example, the underlying type could be an interface:

type Person interface {
  Name() string
}

Why make an exception in Go's syntax just for structs?

Because both type and struct are significant here. You are defining a type with a keyword type. Your type could be anything, all of the following are valid

type MyBool bool
type MyInt int
type StringList []string
type StringListPointer *StringList

And to define a type that contains more than one value, you use the struct keyword.

type MyStruct struct {
    x    MyInt
    y    StringList
    next *MyStruct
}

And you could, technically, have a struct without defining a type. This is not used very often, but it does have its use cases where you only intend to use a particular struct once. This is valid.

x := struct {
    Name  string
    Value int
}{"Hello World!", 10}
fmt.Printf("%+v
", x)