Classes
Keep related state and behavior together, with familiar fields, methods, and concise construction.
class Person {
Name string
func Greet() string {
return "Hello " + this.Name
}
}
person := Person(Name: "Ada")
Generic classes
Define a class once and use it with different value types through Go’s generic type system.
class Box[T] {
Value T
func Get() T { return this.Value }
}
box := Box[int](Value: 42)
fmt.Println(box.Get())
Generic methods
Give a class method its own type parameter so it can work with different value types.
class Echo {
func Identity[T](value T) T {
return value
}
}
echo := Echo()
fmt.Println(echo.Identity[string]("hello"))
Multiple inheritance
Inherit fields and methods from multiple base classes to compose reusable state and behavior into one type.
class Greeter {
func Greet() string { return "hello" }
}
class Logger {
func Log() string { return "logged" }
}
class App : Greeter, Logger {}
app := App()
println(app.Greet(), app.Log())
Polymorphism
Call behavior through a base type and let the concrete class provide the implementation.
class Animal {
func Speak() string { return "unknown" }
}
class Cat: Animal {
func Speak() string { return "meow" }
}
var animal Animal = Cat()
fmt.Println(animal.Speak()) // meow
Error fallback
Handle a function’s returned error at the call site with default values or another function call, including for multiple results.
import "fmt"
func Dimensions() (int, int, error) {
return 0, 0, fmt.Errorf("dimensions unavailable")
}
width, height := Dimensions() ?? 0, 1
Exception handling
GPP turns unhandled errors into exceptions automatically so you can keep the success path readable.
try {
data := os.ReadFile(path)
println(len(data))
} catch os.PathError, os.SyscallError err {
println(err)
} finally {
println("load finished")
}
Overloaded methods
Give related operations one clear name; the compiler selects by argument count and static types.
func Format(value int) string { return "number" }
func Format(value string) string { return "text" }
Format(42)
Format("42")
Named arguments and defaults
Make calls self-documenting and keep common options at their declaration.
func Greet(name string, punctuation string = "!") string {
return name + punctuation
}
Greet(name: "Ada")
Greet(punctuation: "...", name: "Ada")
Extension methods
Add methods to any type without cluttering your code with free floating functions!
extend string, []byte {
func IsEmpty() bool {
return len(this) == 0
}
}
if name.IsEmpty() { ... }
Serialization
One annotation gives your classes typed JSON, YAML, and GOB encoders and decoders.
class User @{encoding.Serializable} {
Id int
Name string
}
json := user.ToJSON()
fromJSON := User.FromJSON(json)
yaml := user.ToYAML()
fromYAML := User.FromYAML(yaml)
gob := user.ToGOB()
fromGOB := User.FromGOB(gob)
Packages
Keep Go imports, functions, and types. A missing package declaration defaults to main, and source folders need not mirror package names.
package demo.people
import "fmt"
func Hello(name string) {
fmt.Println("Hello", name)
}
Constructor methods
Overload init methods to control construction; positional and named arguments match initializer parameters.
class User {
Name string
Age int
func init(name string) {
this.Name = name
}
func init(name string, age int) {
this.Name = name
this.Age = age
}
}
guest := User("Guest")
ada := User(age: 36, name: "Ada")
Object construction
Easier instances of classes and named structs positionally or by field name, with compile-time field and arity checks.
class Person { Name string; Age int }
struct User { Name string; Age int }
person := Person("Ada", 36)
user := User(Name: "Ada", Age: 36)
Static methods
Put class-qualified constructors and helpers next to the type they create.
class User {
Name string
static func Guest() *User {
return User(Name: "Guest")
}
}
guest := User.Guest()
Anonymous structs
Freely return and receive anonymous data shapes without declaring another named struct or class.
user := struct(
Name: "Ada",
Active: true,
Profile: struct(Role: "admin"),
)
fmt.Println(user.Profile.Role)
Typed slices and arrays
Build slices, nested slices, fixed arrays, and class collections with their types up front.
numbers := int[1, 2, 3]
matrix := []int[[1, 2], [3, 4]]
fixed := [3]int[10, 20, 30]
class Label {
Text string
func init(text string) { this.Text = text }
}
labels := Label[("first"), ("second")]
more := numbers.Append(4)
filtered := more.Filter(value => value > 1)
Enums with metadata
Represent finite choices as validated scalar values with ordered members and names.
enum Status string {
Draft
Published
}
status := Status.Published
fmt.Println(status.value, status.name)
Lambdas
Write contextual expression or block lambdas that lower to Go function literals.
activeNames := users
.Filter(user => user.Active)
.Map(user => user.Name)
Annotations and introspection
Abstract away repeating patterns to reduce code duplication with a touch of metaprogramming using annotations!
annotation Table(name string) on class
class Employee @{Table("employees")} {
Name string
}
table := Employee.class.annotations.find(Table)
fmt.Println(table.args[0]) // employees
Regular expressions
Use the regexp(pattern) builtin to match regular expressions in values and switch cases.
path := "/users/42"
matched := regexp(`^/users/[0-9]+$`).MatchString(path)
switch path {
case regexp(`^/users/[0-9]+$`):
println("user path")
}
String interpolation
Place expressions directly in strings and use formatting verbs when needed.
message := "Hello {{user.Name}}"
price := "Total: {{price:.2f}}"
Explicit safe access
Opt in to zero-valued results when a nullable class pointer is nil.
var user *Person
name := user?.Name
greeting := user?.Greet()
Comprehensive Operators
Use compound assignments, increment/decrement, bitwise operations, conditional assignment, and ternary expressions.
count, mask, bits := 10, 1, 0
count += 2 // addition assignment
count -= 1 // subtraction assignment
count *= 2 // multiplication assignment
count %= 4 // remainder assignment
count++ // increment
count-- // decrement
bits |= mask // bitwise OR
bits <<= 1 // shift left
bits &^= mask // clear bits
class Feature {}
var feature *Feature
feature ||= Feature() // assign only if nil
// ternary expression
return feature != nil ? "ready" : "missing"