Basic Gosu
The following Gosu program illustrates basic Gosu code using a familiar Hello World example. The
example uses the built-in print function to write the text
"Hello World" to the default output stream or console:
print("Hello World")Gosu uses the Java type java.lang.String as its native String type to manipulate
texts. You can create in-line String literals just as in Java. In addition, Gosu supports
native in-line templates, which simplify common text substitution coding patterns.
To declare a variable in the simplest
way, use the var statement
followed by the variable name. Typical Gosu code also initializes the
variable by using the equal sign followed by any Gosu expression:
var x = 10
var y = x + x
Although this example does not specify types for the
variables, Gosu is statically typed. All variables have a compile-time
type that Gosu enforces at compile time, even though this example has
no explicit type declaration. Gosu automatically assigns the type int to these variables. Gosu infers
the type int from the
expressions on the right side of the equal signs on lines that declare
the variables. Inferring the type of an item from the expression that
initializes the item is called type inference.
Type inference simplifies Gosu code compared to other statically typed programming languages. Type inference makes typical Gosu code easy to read but retains the power and safety of static typing. For example, take the common pattern of declaring a variable and instantiating an object.
In Gosu, this pattern looks like:
var c = new MyVeryLongClassName()This line is equivalent to the following Java code:
MyVeryLongClassName c = new MyVeryLongClassName();The Gosu version is more readable and concise than the Java version.
Gosu also supports explicit type declarations of variables during declaration by adding a colon character and a type name. The type name could be a language primitive, a class name, or interface name. For example:
var x : int = 3Explicit type declarations are required if you are not initializing the variable on the same statement as the variable declaration. Explicit type declarations are also required for all class variable declarations.
From the previous examples, you might notice another difference between Gosu and Java: no semicolons or other line ending characters. Semicolons are unnecessary in nearly every case, and the standard style is to omit them.
See also
