keyword func

114 views
Skip to first unread message

レミリア・スカーレット

unread,
Apr 27, 2020, 12:46:21 PM4/27/20
to golang-nuts
Why you need to write a "func sum(a, b int) int {...}", not "sum(a, b int) int {...}"?
It seems to me that one could do without func keyword.

Uli Kunitz

unread,
Apr 27, 2020, 2:48:53 PM4/27/20
to golang-nuts
You are correct the func keyword for function definitions is functionally not needed. But it helps readability very much and also allows a natural syntax for anonymous functions and the definition of function types. Another factor is that it simplifies parser programming.

Marvin Renich

unread,
Apr 27, 2020, 3:16:03 PM4/27/20
to golang-nuts
* レミリア・スカーレット <valent...@gmail.com> [200427 12:46]:
> Why you need to write a "func sum(a, b int) int {...}", not "sum(a, b int)
> int {...}"?
> It seems to me that one could do without func keyword.

I believe another reason is that the Go language designers decided that
every top-level syntax element begins with a keyword: package, import,
type, const, var, func. Perhaps this is just for convenience of
parsing, but it greatly simplifies human parsing (readability) as well.

...Marvin

Ben Hoyt

unread,
Apr 27, 2020, 7:02:39 PM4/27/20
to golang-nuts
Yeah, I agree with Marvin. "func" is also needed for anonymous functions and defining function types. This would be quite weird (and probably not easily parseable):

    add := (a, b int) int { return a+b }
    type adder (a, b int) int

Most importantly for me, explicit syntax for this allows me to easily use simple tools like grep or Ctrl-F to find function definitions -- I can just do a text-search for "func Foo". In C and other languages that's hard, you have to search for "{startOfLine}{returnType} Foo". But without regex search it's hard to search for startOfLine, and often you don't know the returnType.
Reply all
Reply to author
Forward
0 new messages