Grouped functions...

287 views
Skip to first unread message

Trig

unread,
Feb 11, 2021, 7:09:15 PM2/11/21
to golang-nuts
So, in Go... you can either define imports, constants, types, variables one at a time... or you can group them using brackets.  Why was it decided not to be able to do that with functions?  Just curious.

func (
     main() {
        fmt.Println(helloWorld())
     }

     helloWorld() string {
        return "hello, world..."
     }
)

Ian Lance Taylor

unread,
Feb 11, 2021, 8:22:39 PM2/11/21
to Trig, golang-nuts
One reason is that it doesn't work very well for methods. It could be
done, of course, but the resulting code doesn't look quite right.

Ian

Paul Förster

unread,
Feb 12, 2021, 10:05:28 AM2/12/21
to Trig, golang-nuts
Hi Trig,

I'm new to the list and I'm a Go newbie, but
I guess it's because:

var (
a int,
b string,
...
)

is just a syntactical grouping, which var also be written as:

var a int
var b string
...

while

func (
func x() {
...
}
func y() {
...
}
)

would affect scope. In the above x() and y() would be local functions to an unnamed function. Defining the scope is what packages are for. I'd really love to see local functions, though, not for real scope usage but for clarity of coding.

Also, grouping functions inside func (...) wouldn't make sense because that'd only mean that you'd basically indent almost all of your code unnecessarily by one tab, or whatever you use.

Cheers,
Paul

Brian Candler

unread,
Feb 12, 2021, 11:54:51 AM2/12/21
to golang-nuts
> I'd really love to see local functions, though, not for real scope usage but for clarity of coding.


But if you're not interested in accessing variables in the enclosing scope, you might as well put them as non-exported functions at the top level.
Reply all
Reply to author
Forward
0 new messages