10

Just out of curiosity, why does the golang place the type specifier after the variable name like below. Have to? Or happen to?

type person struct {
    name string
    age  int
}

Why not just like this? It's more natural IMHO, and it saves the type keyword.

struct person {
    string name
    int age
}
3
  • 6
    You can found some reasons here: blog.golang.org/gos-declaration-syntax Commented Nov 20, 2016 at 8:41
  • 2
    The resource @sisoft provided is excellent (but doesn't explain where it comes from). My hunch is the following: since Go has three ancestors (CSP, Pascal/Oberon, and C) I suppose that the variable declaration and definition style is inherited from Pascal/Oberon line. Commented Nov 20, 2016 at 8:42
  • Second part of your question is simple: type defines more than just structs. Commented Nov 20, 2016 at 8:46

1 Answer 1

12

I think the Go programming language follows these principles:

  • declarations start with a keyword, so that the parser can be implemented with a single token look-ahead (like in Pascal)
  • the rest of the declaration follows the English grammar, with every redundant word left out (also like in Pascal, but with fewer keywords)

Examples:

  • The type Frequency is a map indexed by string, mapping to int
    type Frequency map[string]int
  • The type Point is a struct with two fields, x and y of type int
    type Point struct { x, y int }

The above sentences focus more on the names than on the types, which makes sense since the names convey more meaning.

If I had to explain to novice programmers how to write declarations in Go, I would let them first describe it in plain English and then remove every word that might even seem redundant.

Up to now, I didn't find any contradictions to these rules.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.