Start from a main routine: Difference between revisions

Added Go
m (→‎{{header|C}}: Remove vanity tags)
(Added Go)
Line 131:
 
* Right click the MMain module, then select Startup class from the context menu
 
=={{header|Go}}==
In Go all executable programs must have a main package which includes a function called main() with no parameters nor return value.
 
However, execution doesn't necessarily begin with main() itself. If there are top-level functions called init() with no parameters nor return value, these are executed first in declaration order and they can call other functions including main() itself.
 
Here's an example which illustrates this behavior. Note that main() gets called twice, first by the second init() function and then automatically by the runtime.
 
In practice, init() functions are generally used to initialize top-level variables which cannot (or cannot easily) be initialized in situ rather than to pre-empt the main() function in this way.
<lang go>package main
 
import "fmt"
 
var count = 0
 
func foo() {
fmt.Println("foo called")
}
 
func init() {
fmt.Println("first init called")
foo()
}
 
func init() {
fmt.Println("second init called")
main()
}
 
func main() {
count++
fmt.Println("main called when count is", count)
}</lang>
 
{{out}}
<pre>
first init called
foo called
second init called
main called when count is 1
main called when count is 2
</pre>
 
=={{header|J}}==
9,490

edits