Writing Lyth
Lyth is a programming language that compiles to readable Go and builds with the go command. It
keeps Go’s semantics and Go’s spelling for everything Go has (func, :=, int, map[K]V,
[T] generics), and adds what Go lacks: throws and ? instead of if err != nil, nullable
types, if and when as expressions, lambdas, named and default arguments. Every Go package
works with its exact Go names.
This page is for people and for AI coding agents; lyth guide prints it for the installed
version. Lyth changes between versions, so when this guide or the compiler disagrees with what
you remember about Lyth, they are right.
How to work
Section titled “How to work”- A Lyth project is a Go module:
go.modat the root,.lythfiles in package directories,_test.lythfiles beside them.lyth initcreates one. Imports come fromgo.modas in Go;lyth mod tidyadds the modules your.lythfiles import (lyth mod vendorvendors them). The//lyth:versionline ingo.modis the Lyth version the module is written for: keep it, and don’t change it by hand (lyth fix -lang=X.Yraises it). - Run
lyth checkafter each change and fix what it reports before writing more. It is fast, and test files are included.lyth fmtlays the files out canonically. Diagnostics point at.lythlines and speak Lyth; many end with ahint:that gives the exact edit. lyth fixapplies the edits that only respell code: older Lyth syntax, and Kotlin and Go spellings of Lyth constructs (the table below). When a project shows many errors after a Lyth upgrade, runlyth fixfirst, then fix the rest by hand.lyth runruns a program (lyth run file.lyth, or a package directory; program arguments go after--),lyth testruns the tests (go testflags work),lyth vetrunsgo veton the generated code. A profile fromlyth test -coverprofile=c.outnames.lythfiles: read it withlyth cover -func=c.out(go tool cover -funccannot parse Lyth).lyth gen -stdout file.lythprints the Go a file becomes. Use it when you are unsure what a construct does.lyth generate ./...runs the//go:generatelines of.lythfiles (go generatereads only.gofiles).- Keep the work in
.lythfiles. Don’t edit the generated Go (in.lyth/gen), and don’t write.gofiles to get around a Lyth error: a package cannot mix Lyth and non-test Go files, and Lyth errors have Lyth fixes. - Go documentation applies as is:
go doc net/http.Servershows what Lyth callshttp.Server.
The language at a glance
Section titled “The language at a glance”import "errors"import "fmt"import "strconv"import "strings"import "lyth/coll"
enum Role { Admin, Member }
struct User { Name: string Age: int Role: Role Email: string?}
func User.Label(): string = "${self.Name} (${self.Age})"
func *User.Birthday() { self.Age++}
struct NotFound { Name: string}
func *NotFound.Error(): string = "no user named ${self.Name}"
func parseAge(s: string): int throws { n := strconv.Atoi(strings.TrimSpace(s)).wrap("age ${s}")? if n !in 0..150 { throw errors.New("age ${n} is out of range") } return n}
func find(users: []User, name: string): *User throws { for i, u in users { if u.Name == name { return &users[i] } } throw &NotFound(Name = name)}
func main() throws { users := [ User(Name = "ada", Age = parseAge("36")?, Role = Role.Admin), User(Name = "bob", Age = parseAge(" 41 ")?, Role = Role.Member, Email = "bob@example.com"), ] ada := find(users, "ada")? ada.Birthday() fmt.Println(ada.Label())
for u in users { role := when u.Role { Admin -> "admin" Member -> "member" } fmt.Println("${u.Name}: ${role}, ${u.Email ?: "no email"}") }
names := users.Filter { it.Age > 40 }.Map { strings.ToUpper(it.Name) } fmt.Println(names)
guest := find(users, "eve") catch (e: *NotFound) { fmt.Println(e.Error()) &User(Name = "guest") }? fmt.Println(guest.Label())
age := parseAge("abc") catch (err) { fmt.Println(err) 0 } fmt.Println(age)}import ( "errors" "fmt" "lyth/coll" "os" "strconv" "strings")
type Role int
const ( RoleAdmin Role = iota RoleMember)
// String returns the name of the Role entry.func (r Role) String() string { switch r { case RoleAdmin: return "Admin" case RoleMember: return "Member" } return "Role(" + strconv.Itoa(int(r)) + ")"}
// MarshalText returns the wire name of the Role entry.func (r Role) MarshalText() ([]byte, error) { switch r { case RoleAdmin: return []byte("admin"), nil case RoleMember: return []byte("member"), nil } return nil, fmt.Errorf("invalid Role %d", int(r))}
// UnmarshalText sets r to the Role entry with the given wire name.func (r *Role) UnmarshalText(text []byte) error { switch string(text) { case "admin": *r = RoleAdmin case "member": *r = RoleMember default: return fmt.Errorf("invalid Role %q", text) } return nil}
type User struct { Name string `json:"name"` Age int `json:"age"` Role Role `json:"role"` Email *string `json:"email,omitzero"`}
func (u User) Label() string { return u.Name + " (" + strconv.Itoa(u.Age) + ")" }
func (u *User) Birthday() { u.Age++}
type NotFound struct { Name string `json:"name"`}
func (n *NotFound) Error() string { return "no user named " + n.Name }
func parseAge(s string) (int, error) { n, err := strconv.Atoi(strings.TrimSpace(s)) if err != nil { return 0, fmt.Errorf("age %s: %w", s, err) } if n < 0 || n > 150 { return 0, errors.New("age " + strconv.Itoa(n) + " is out of range") } return n, nil}
func find(users []User, name string) (*User, error) { for i, u := range users { if u.Name == name { return &users[i], nil } } return nil, &NotFound{Name: name}}
func run() error { v, err := parseAge("36") if err != nil { return err } v3 := User{Name: "ada", Age: v, Role: RoleAdmin} v2, err := parseAge(" 41 ") if err != nil { return err } users := []User{ v3, {Name: "bob", Age: v2, Role: RoleMember, Email: new("bob@example.com")}, } ada, err := find(users, "ada") if err != nil { return err } ada.Birthday() fmt.Println(ada.Label())
for _, u := range users { var role string switch u.Role { case RoleAdmin: role = "admin" case RoleMember: role = "member" default: panic("lyth: no when branch for this Role (example.lyth:55:17)") } email := "no email" if u.Email != nil { email = *u.Email } fmt.Println(u.Name + ": " + role + ", " + email) }
names := coll.Map(coll.Filter(users, func(it User) bool { return it.Age > 40 }), func(it User) string { return strings.ToUpper(it.Name) }) fmt.Println(names)
guest, err := find(users, "eve") if err != nil { if e, ok := errors.AsType[*NotFound](err); ok { fmt.Println(e.Error()) guest = &User{Name: "guest"} } else { return err } } fmt.Println(guest.Label())
age, err := parseAge("abc") if err != nil { fmt.Println(err) age = 0 } fmt.Println(age) return nil}
func main() { if err := run(); err != nil { fmt.Fprintln(os.Stderr, "error:", err) os.Exit(1) }}ada (37)ada: admin, no emailbob: member, bob@example.com[BOB]no user named eveguest (0)age abc: strconv.Atoi: parsing "abc": invalid syntax0Declarations
Section titled “Declarations”- Imports:
import "fmt", or a group with one per line:import ( "fmt"; h "net/http" )written over several lines. Rename as in Go:import h "net/http",import _ "path". - Functions:
func add(a: int, b: int): int { return a + b }, or with one expression,func add(a: int, b: int): int = a + b. Parameters and results arename: Typeand: Type. An unexported expression-bodied function may omit its result type (func sq(n: int) = n * n). A block body returns withreturn; the last expression is not returned by itself. - Several results:
func split(s: string): (string, string),return a, b. Results may be named as in Go,func split(n: int): (q: int, r: int)(a barereturnreturns them), and withthrows,func *W.Write(p: []byte): (n: int) throws:deferblocks can setn. - Locals:
x := 1declares a mutable variable,x = 2assigns,x: int64 = 0orx: int64(the zero value) when the type matters.a, b := f()anda, b = b, a + bwork as in Go. There is novalorvarinside functions. - Package level:
var Default = "x",var mu: sync.Mutex(the zero value),const Max = 10.constalso works inside a function. Groups are Go’s, withname: Typeentries:const ( FlagA: uint = 1 << iota; FlagB )andvar ( ErrA = errors.New("a"); count: int ), one per line; an entry with only a name repeats the one above with the nextiota.func init() { ... }runs beforemain, as in Go; a package may have several. - Files of the package directory are embedded as in Go:
//go:embed schema.sqlon the line beforevar schema: string(or[]byte, orembed.FSfor several files), with no initializer.//go:noinlineand the other compiler directives go on the line before afunc. - Parameters, loop variables,
catchbindings, andselfare read-only.:=may replace a parameter with a value of its type derived from it, as Go code does:ctx, cancel := context.WithTimeout(ctx, d),g, ctx := errgroup.WithContext(ctx),name := strings.TrimSpace(name). - Visibility is Go’s: a capitalized name is exported. Write Go-style names yourself:
UserID,NewServer,ID. - Structs:
struct User { ... }with oneName: Typefield per line. A struct may also be declared inside a function, for table tests and request bodies (struct tc { in: string; want: int }); it has no methods. Exported fields get lower-cameljsontags automatically (UserID→userID,IDs→ids,HTTPServer→httpServer), and a nullT?field is left out of the JSON. A name likeETagwarns (W0008): give it a tag such asjson:"etag".json:",string"keeps the automatic name, andjson:""keeps Go’s: the field is untagged in Go and encodes as"ETag". Construct by calling the type:User(Name = "a", Age = 3), positionally with every field, and&User(...)for a pointer. Go structs take named arguments:&http.Server(Addr = ":8080"). - Methods are declared outside the struct:
func User.Hello(): string(value receiver),func *User.Rename(n: string)(pointer receiver). The receiver isself, and fields and methods are reached only through it:self.Name,self.validate(). A bareNamein a method is an error, as in Go. A method that changes the receiver’s fields needs*. - Embedding is Go’s: a type alone on a line of a struct (
http.ResponseWriter,sync.Mutex,pb.UnimplementedGreeterServer,Base). Promoted members are reached through the value orself(self.Lock()); the field is named after the type (self.ResponseWriter). An embedded struct is flattened into JSON.Store?embeds an interface that may stay null (partial fakes). - Interfaces:
interface Shape { Area(): float64 }. Conformance is structural, as in Go;struct Circle : Shape { R: float64 }also declares it, and the compiler checks it. - Generics:
func Max[T: cmp.Ordered](a: T, b: T): T,struct Page[T] { Items: []T },func Page[T].First(): T. Calls infer type arguments; write them in brackets when nothing determines them:errors.AsType[*NotFound](https://github.com/lyth-lang/lyth/tree/main/docs/guide/err). Type sets are Go’s:[T: int | float64],interface Number { ~int | ~float64 }.T?on a type parameter is not supported: return(T, bool)as Go does. - Extension functions:
func string.Shout(): string = strings.ToUpper(self) + "!". - Defined types and aliases, as in Go:
type UserID int64,type Role string,type Set[T: comparable] map[T]struct{}(a new type:UserID(n)converts, and methods can be declared on it), andtype Handler = (http.ResponseWriter, *http.Request) -> unit throws(another name for the same type; generic too:type Set[T: comparable] = map[T]bool). Function types may name their parameters:(name: string, depth: int) -> bool. Structs and interfaces keepstruct Name { ... }andinterface Name { ... }. - Enums:
enum Color { Red, Green }, used asColor.Red, orRedinsidewhen c { ... }. JSON carries the entry name in lower camel case ("red") and rejects anything else. For fixed wire values, use a string-backed enum:enum Plan: string { Free = "free", Pro = "pro" }(Go’stype Plan string; pgx anddatabase/sqlstore it as text). A string-backed enum has no zero value unless an entry is"".sealed interface Shape { ... }is implemented only by structs of the same package that declare it. - Default and named arguments:
func connect(host: string, port: int = 5432), called asconnect("db", port = 6543). Go functions take positional arguments only.
- Go’s names:
int,int64,float64,string,bool,byte,rune,any,error,[]T,[N]T,map[K]V,chan T,*T, andstruct{}(valuestruct{}{}). - Function types are
(A, B) -> R,(A) -> unit, and(A) -> R throwsfor one that can fail. T?is nullable.[]User?is a slice of nullable users:?belongs to the element. Slices and maps themselves are never nullable (([]T)?is an error), but as in Go one that was never assigned (xs: []int, a field left out at construction) is nil: it reads as empty,encoding/jsonwrites it asnullwhere a literal[]gives[], and writing to a nil map panics (start with[:]ormake).xs == nullandxs ?: fallbacksee only the nil one.- Numbers never convert implicitly:
float64(n),int64(x). - Literals take their type from context:
xs: []int = [],m: map[string]int = [:],["a": 1]. Go’s typed literals work too:[]int64{1, 2},map[string]any{"ok": true}. - Strings:
"Hi ${name}, ${n + 1}"interpolates; a"..."string stays on one line (\nfor line breaks). Backtick strings are raw, as in Go: no escapes and no templates, so${name}in one is plain text (warning W0012 whennameis a variable). Concatenate to insert values. m[k]andch.receive()give the zero value when nothing is there, as in Go; when the value type has none (a struct with a non-null pointer field, a*User), they give aT?that is null then:job := jobs.receive() ?: break.- Slicing is Go’s:
xs[lo:hi],xs[lo:hi:max]. Conversions areT(x), and(*T)(p)for a pointer type (unsafe.Pointerworks as in Go).
Errors
Section titled “Errors”- A function that can fail is
func f(): T throws, Go’s(T, error). f()?returns the error to the caller.throw errreturns one. Add context where it fails:f().wrap("loading ${path}")?wraps the error only whenf()fails (also withcatch (err), which then sees the wrapped error);err.wrap("...")wraps an error value.f() catch { fallback }, orf() catch (err) { ...; fallback }, handles it in place.f() catch {}ignores it explicitly.- In a lambda that can fail (a callback such as
g.Go { }or a transaction function), a barereturnmeans success, also insidecatch, where it drops the error (warning W0013). Writethrow errto fail, orcatch (_) { return }to succeed on purpose. f() catch (e: *NotFound) { ... }handles one error type (through wrapping); it must end with?or a finalcatchfor the other errors. For an error already in a variable, usenf, ok := errors.AsType[*NotFound](https://github.com/lyth-lang/lyth/tree/main/docs/guide/err):err is *NotFoundsees only the outermost error and misses a wrapped one (warning W0007).- An error that is not handled is a compile error.
func main() throwsprints the error and exits with status 1, and tests may bethrows. - In a
throwsfunction,defer f.Close()?makes a failure of the deferred call the function’s error, unless the function is failing already.?andthrowinsidedefer { ... }do the same:defer { r := recover(); if r != null { throw fmt.Errorf("panic: %v", r) } }. n, err := strconv.Atoi(s)also works, as in Go.
Null safety
Section titled “Null safety”- A
T?needs a check before member access:if u != null { u.Name }(a smart cast), oru?.Name,u?.Name ?: "anon",u!!(panics on null).?.is only this safe call: to propagate an error and then select, write(f()?).Name, orf()??.Namewhen the result may also be null. User?is an optional value: it never changes, sou.Name = xis an error, and==compares contents. A*Userbecomes one only as a copy,*p(users[i]for&users[i]). To change oneUserthat others see, use a nullable pointer,*User?.x := f() ?: returnexits early on null.- Smart casts apply to parameters,
self, and locals. A reassigned local stays smart-cast until its next assignment (node = node.Nextinsidewhile node != nullworks, and so doesif u == null { u = guest }beforeu.Name), unless a lambda assigns it or&uis taken. For a field or a package-level variable, copy it into a local first. v, err := f()giveserrthe typeerror?: check it beforethrow err. A success value without a zero value isT?there (null whenffails); preferv := f()?.- Values from Go packages are usable as non-null.
Control flow
Section titled “Control flow”- No parentheses around conditions, braces always:
if c { } else if d { } else { },while c { },while true { }. - Loops:
for x in xs,for i, x in xs,for k, v in m,for i in 0..<n,for i in 1..n, and Go iterators:for k in maps.Keys(m),for k, v in maps.All(m). There is norange. Go’s three-part loop works for other steps:for i := n - 1; i >= 0; i-- { }. iftakes Go’s init statement:if v, ok := m[k]; ok { },if r := recover(); r != null { }.ifandwhenare expressions:label := if n > 0 { "pos" } else { "neg" }.when code { 200, 204 -> a; in 500..599 -> b; else -> c }, andis T ->branches over interfaces. Awhenover an enum or a sealed interface must cover every case or haveelse; over a nullable one, every case andnull(null -> ...) make it exhaustive too.x in xs,k in m,"@" in email,code in 200..299, and!in.- Labels:
outer@ for x in xs { ... break@outer }.breakinsidewhenexits the loop. - Lambdas:
{ a, b -> a + b },{ it * 2 }, and a trailing lambdaxs.Map { it * 2 }. A loop orifheader cannot end in a trailing lambda: parenthesize the call. A lambda with several results returns them withreturn a, b. go { ... },defer { ... },defer f.Close() catch {}.- Channels:
make(chan int, 10),ch.send(v),ch.receive(),v, ok := ch.receive(),ch.close(),for v in ch, andselect { v := ch.receive() -> ...; else -> ... }.
- Tests are Go tests in
_test.lythfiles:func TestParse(t: *testing.T) { ... }, and a test may bethrows. A test file inpackage x_testtests packagexfrom outside, importing it as other code does.lyth test ./...runs them, withgo testflags such as-vand-run. - A table test declares its case struct in the test function:
struct tc { in: string; want: int }, thenfor c in [tc(in = "1", want = 1)] { ... }. go vetruns with the tests and requires a constant format string: writet.Errorf("got %d, want %d", got, want), ort.Error("got ${got}, want ${want}")with a template, never a template insidet.Errorf(lyth checkwarns, W0010).
Coming from Go
Section titled “Coming from Go”What Go programmers write by habit, and the Lyth for it:
| Go | Lyth |
|---|---|
func (u *User) Rename(n string) |
func *User.Rename(n: string), with self for the receiver |
x int, func f() int |
x: int, func f(): int |
Point{X: 1, Y: 2} |
Point(X = 1, Y = 2) |
gin.H{"error": msg}, url.Values{"q": {"go"}} |
gin.H(["error": msg]), url.Values(["q": ["go"]]) |
for i, x := range xs |
for i, x in xs |
for i := 0; i < n; i++ |
the same, or for i in 0..<n |
for { }, for cond { } |
while true { }, while cond { } |
ch <- v, <-ch, close(ch) |
ch.send(v), ch.receive(), ch.close() |
go func() { ... }() |
go { ... } |
nil |
null |
if err != nil { return err } |
f()? |
defer func() { if cerr := f.Close(); cerr != nil && err == nil { err = cerr } }() |
defer f.Close()? |
[T cmp.Ordered] |
[T: cmp.Ordered] |
var x = 1 in a function |
x := 1 |
var mu sync.Mutex (package level) |
var mu: sync.Mutex |
type tc struct { ... } in a function |
struct tc { ... } in the function |
[]struct{ in string }{...} |
declare struct tc { in: string }, then [tc(in = "a")] |
switch |
when |
ctx, cancel := context.WithTimeout(ctx, d) |
the same: := may replace a parameter with a value derived from it |
r = r.WithContext(ctx) (assigning a parameter) |
r := r.WithContext(ctx) |
strings.FieldsFunc(s, func(r rune) bool { ... }) |
strings.FieldsFunc(s) { r -> ... } |
func(string) bool, func(string) error (types) |
(string) -> bool, (string) -> unit throws |
x.(T), v, ok := x.(T), _, ok := x.(T) |
x as T, v := x as? T, ok := x is T |
switch x := v.(type) { case int: ... } |
when x := v { is int -> ... } |
const ( A T = iota; B ), var ( x int ) |
const ( A: T = iota; B ), var ( x: int ) |
func f() (n int, err error) (named results) |
func f(): (n: int) throws |
| a label on its own line above a loop | outer@ for ... |
Coming from Kotlin
Section titled “Coming from Kotlin”| Kotlin | Lyth |
|---|---|
fun f(x: Int): Int |
func f(x: int): int |
val x = 1, var y = 2 |
x := 1, y := 2 |
Int, String, Boolean, List<T>, Map<K, V> |
int, string, bool, []T, map[K]V |
fun <T> f(), Box<T> |
func f[T](), Box[T] |
this |
self |
"$name" |
"${name}" |
"""Hi ${name}""" |
"Hi ${name}"; backtick strings are raw and do not interpolate |
class User(val name: String) |
struct User { Name: string } |
| methods inside the class | func User.Greet() at top level |
companion object, static methods |
package functions (NewUser) |
listOf(1, 2), mapOf("a" to 1) |
[1, 2], ["a": 1] |
when (val x = f()) |
when x := f() |
for (x in xs) |
for x in xs |
try { } catch (e: E) { } |
f() catch (e: *E) { } catch { }, or end with ? |
xs.filter { }.map { } |
import "lyth/coll", then xs.Filter { }.Map { } |
Not in Lyth
Section titled “Not in Lyth”Packages mixing Lyth and non-test Go files (put the Go code in a package of its own),
anonymous struct types (declare a struct, also inside a function), and T? on type parameters
(return (T, bool)) are left out by design. The compiler reports each of these with a way
around it.
Changes between versions
Section titled “Changes between versions”Lyth’s syntax has changed and will change again. The compiler keeps recognizing older forms and
reports each with the edit to today’s form; lyth fix applies those edits to a whole module.
The table lists older Lyth forms and the Go and Kotlin habits the compiler recognizes.
| Older form | Write instead | lyth fix |
|---|---|---|
fun f() |
func f() |
yes |
val x = e, var x = e (in a function) |
x := e |
yes |
val x: T = e |
x: T = e |
yes |
val X = e (package level) |
var X = e |
yes |
Int, String, Boolean, Long, Double, … |
int, string, bool, int64, float64, … |
yes |
List<T>, Map<K, V>, Chan<T> |
[]T, map[K]V, chan T |
yes |
fun <T> f(), struct Box<T>, f<T>(x) |
func f[T](), struct Box[T], f[T](https://github.com/lyth-lang/lyth/tree/main/docs/guide/x) |
yes |
[T cmp.Ordered] |
[T: cmp.Ordered] |
yes |
this |
self |
yes |
nil |
null |
yes |
"$name", where name is a variable |
"${name}", or "\$name" for the text |
no: both are possible |
for (x in xs) |
for x in xs |
yes |
when (val x = e) |
when x := e |
yes |
(a, b) = f() |
a, b = f() |
yes |
Point{X: 1} |
Point(X = 1) |
yes |
gin.H{"k": v} |
gin.H(["k": v]) |
yes |
strings.split(s, ",") |
strings.Split(s, ",") |
yes |
go func() { ... }() |
go { ... } |
yes |
ch <- v, <-ch |
ch.send(v), ch.receive() |
yes |
const userKey ctxKey = 1 |
const userKey: ctxKey = 1 |
yes |
catch (e: error) { ... } |
catch (e) { ... }: it handles every error |
yes |
catch (e: PathErr) where only *PathErr has the Error method |
catch (e: *PathErr) |
yes |
val, var as names (val := m[k]) |
another name, such as value |
no: a name to choose |
try { ... } catch (e: Exception) { ... } |
f() catch (e) { ... } on each call that can fail |
no |
outer: for ..., break outer (also with the label on its own line) |
outer@ for ..., break@outer |
yes |
func(string) bool (a Go function type) |
(string) -> bool |
yes; func(...) error is a hint: (...) -> unit throws, or -> error? |
import "net/http" as h |
import h "net/http" |
yes |
typealias Handler = (Ctx) -> unit |
type Handler = (Ctx) -> unit |
yes |
type User struct { ... }, type Box[T any] struct |
struct User { ... }, struct Box[T: any] |
yes (the name, keyword, and type parameters) |
Name Type (a Go struct field), X, Y int |
Name: Type, one field per line |
yes |
func f(name string, a, b int) int |
func f(name: string, a: int, b: int): int |
yes |
Area() float64 in an interface |
Area(): float64 |
yes |
func f() (int, error), func f() error |
func f(): int throws, func f() throws |
no: the returns change |
func (p *T) M() |
func *T.M(), and self in the body |
no |
a field or method by bare name in a method (Count++, validate()) |
self.Count++, self.validate() |
yes, unless the name also names a package-level declaration or import there |
automatic json key iDs for IDs, urLs for URLs, iPv4 for IPv4 |
the key is now ids, urls, ipv4; tag json:"iDs" keeps the old one (W0009) |
no: a wire change |
a null T? field encoded as null |
it is left out (omitzero); tag json:"name" keeps null |
no: a wire change |
a T? passed to a Go any parameter arrived as a pointer (*string) |
it arrives as its value, or a nil interface when null; pass &x where Go writes through a pointer |
no: a run-time change |
| an enum encoded as its number in JSON | its name ("pendingReview"); declare MarshalJSON and UnmarshalJSON to keep numbers |
no: a wire change |
n, err := strconv.Atoi(s) then throw err or passing err as error without a check |
if err != null { throw err }: the destructured error is error? (E0305, E0401 otherwise) |
no: a check to add |
lyth run main.lyth inside a module ran the file’s whole package |
it runs that file alone, as go run main.go does; lyth run . runs the package |
no: a command to change |
json:"" on a field kept an empty tag |
the Go field is untagged, so encoding/json uses the field name | no: a wire change only where the tag was written |
a field or method len, init, … was len_, init_ in Go |
it keeps its name; Go code of the package uses x.len |
no: Go code to change |
f()?.name on a call that can fail (propagate, then select) |
(f()?).name; ?. is only the safe call |
yes |
f().wrap("ctx") used as an error value, on a call returning only an error (it wrapped even a nil error) |
f().wrap("ctx")? or catch, which wrap only on failure; or store a value first: e := f(), then e.wrap("ctx") |
no: the meaning changes |
a *T or *T? passed or assigned where T? is expected |
a copy: *p (users[i] for &users[i]), or if p != null { *p } else { null } |
no: the copy no longer follows changes to *p; a hint gives the edit |
Topics
Section titled “Topics”lyth guide <topic> prints the documentation of this version:
tour— the language by examplego— Lyth for Go programmers: each feature next to the Go it replacescheatsheet— Lyth syntax next to the Go it compiles tointerop— Go packages, modules, and Lyth packages seen from Gotesting— tests, benchmarks, and fuzzingtooling— thelythcommand, diagnostics, editors, and buildslanguage— the language referencetypes— the type system: nullability, platform types, genericserrors— error handling in depthcollections— thelyth/collcollection functions