Programming Languages - Main
main is the entry point for many languages:
- either a
main()function or in other forms, like the__main__block in Python. main()function:- commonly has no returns, but returns an
intin C/C++. - some with special requirements, e.g. must be in a class in Java, must be in
package mainin go.
- commonly has no returns, but returns an
By Language
C++
main() returns an int to indicate exit status; 0 if there's no error.
int main(int argc, char** argv) {
// ...
return 0;
}
argc: argument countargv: argument vector
Java
Java code must live in a class.
There's no return value from main(), use System.exit(int status) in case of errors.
class Foo {
public static void main(String args[]) {
// ...
}
}
Kotlin
Similar to Java, however it does not have to be in a class, the compiler will wrap it in a class com.example.HelloWorldKt for a file HelloWorld.kt.
package com.example
fun main() {
println("Hello, World!")
}
Python
if __name__ == "__main__":
# running directly
else:
# imported
Rust
env::args() provides access to raw command-line arguments.
use std::env
fn main(){
for argument in env::args() {
println!("{}", argument);
}
}
Go
In Go, main() function must be in the main package.
There's no parameters passed to main(); os.Args provides access to raw command-line arguments.
package main
import (
"os"
)
func main() {
args := os.Args
// ...
}
JavaScript
JavaScript does not have a main function. The entry point is the beginning of the code.