v0.14.0
Language
Add support multi-case switch statement.
rsswitch(a) { case 1, 2: println("a"); case 10, 20: println("b"); default: println("c"); }Enum literals can omit the type when the type can be inferred.
rsenum Color { Red, Green, Blue, } let color: Color = .Red; fn value(color: Color): int { // ... } value(.Red);
Stdlib
- Add
std.crypto.AssociatedOidinterface. - Add
std.crypto.aes,std.crypto.chacha20,std.crypto.ecdsa,std.crypto.ed25519,std.jwtmodules. - Add
std.crypto.BlockPadding,std.math.BigInt. - Add
std.io.Bytes.chunksmethod. - Add
std.io.Bytes.push,std.io.Bytes.popmethods.
Internal
- Fixed
switchstatement maybe caused JIT to not work. (tests\compile-err\switch\passed\nested.nv)
v0.13.0
Language
Add support for keyword arguments use in generic functions.
Cast to the source type
nvtype A = int; type B = A; let a: A = 1 as A; let b: B = 1 as B; let n = b as int; // cast to the source typeAdd support
x?.(type)syntaxnvlet a: Any? = 10; assert_eq a?.(int), 10;Add support import global var
nvimport std.net.http.NotFound; let status = NotFound;
Stdlib
- Remove
std.json.from_string,std.json.from_bytes,std.json.from_readermethods, usestd.json.parseinstead. - Remove
std.xml.from_string,std.xml.from_bytes,std.xml.from_readermethods, usestd.xml.parseinstead. - Remove
std.yaml.from_string,std.yaml.from_bytes,std.yaml.from_readermethods, usestd.yaml.parseinstead. - Improve
std.process,std.regex. - Rename
std.decimal.Decimal.from_stringtostd.decimal.Decimal.parse. - Use
std.templateto render file list instd.net.http.server.FileSystem. - Add support custom filter/function/tester for
std.template. - Move
std.io.StringBuffertostd.str.StringBuffer. - Rename
std.io.StringBuffer.pushtostd.io.StringBuffer.push_string. - Add
std.io.StringBuffer.push,std.io.StringBuffer.popmethods. - Add
StatusCode.is_ok,StatusCode.is_success,StatusCode.is_client_error,StatusCode.is_server_error,StatusCodeis_redirectionmethods. - Improve
string.bytesfor better performance. - Remove
std.base64.decode_to_string,std.base64.encode_bytes,std.base64.encode_stringmethods. - Add
std.base64.Base64Encoder,std.base64.Base64Decoder. - Add
std.net.http.CookieKey.from_bytes,std.net.http.CookieKey.bytesmethods. - Add support for serialize/deserialize
std.io.Bytes. - Rename
std.time.DateTime.nowtostd.time.DateTime.now_utc. - Remove
std.time.DateTime.timezonemethod. - Add
std.time.DateTime.offsetmethod to get the offset from UTC in seconds. - Change the argument of
std.time.DateTime.to_offsetmethod' to UTC seconds. - Remove
std.time.parse,std.time.now,std.time.from_timestampfunctions. - Add
std.time.TimeZone. - Add
std.time.DateTime.to_timezonemethod to convert theDateTimeto a specific timezone. - Add
std.net.http.Status.as_int,std.net.http.Status.from_intmethods. - Improve
std.regexto remove Navi wrapping code. - Improve
std.envto remove Navi wrapping code. - Improve
std.fsto remove Navi wrapping code. - Remove
std.fs.open,std.fs.create,std.fs.write_bytesfunctions. - Change the return value of
std.fs.globandstd.fs.read_dirfunctions to a iterator. - Remove
std.fs.Metadata.newmethod usestd.fs.metadatainstead. - Add
std.hexmodule. - Remove
std.io.Bytes.encode_to_stringmethod. - Add
std.rand.RandReader. - Rename
std.io.Bytes.concattostd.io.Bytes.append. - Rework
std.crypto.- Add
Hashinterface. - Add
md4,md5,sha1,sha2,ripemd,sha3,blake2,blake3sub modules. - Add
hmac,rsasub modules.
- Add
Internal
- Alloc defer closure in the function stack.
- Improve pass generic params to the native functions.
v0.12.0
Language
Add support for convert error types with try statement.
Add support for method as static closure.
Add support for implicit conversion of an interface to its parent interface.
Add support for cast an interface to its parent interface.
Add support for unescape unicode sequences.
Add support for
let elsestatement.rslet a: int? = 10; let b = a { panic "unreachable"; } assert_eq b, 10;Add support for
try?for expressions that don't return a value.Add support for accessing char at specific positions in a string using the
s[x]syntax.rslet s = "hello"; assert_eq s[0], 'h'; assert_eq s[1], 'e';Add support for custom iterator.
Add support for destructuring assignment.
rsstruct Point { x: int, y: int, } let p = Point {1, 2}; let Point { x, y } = p; assert_eq x, 1; assert_eq y, 2;
Stdlib
- Add
std.io.Seekinterface. - Add
std.io.pipemethod to creates a synchronous in-memory pipe. - Implement
Debugforstd.io.Bytes,std.decimal.Decimal. - Add
std.compress,std.mime,std.net.http,std.net.http.date,std.net.http.server,std.net.http.client.websocket,std.templatemodules. - Rework
std.net,std.net.http.clientmodules. - Fix deserialize to union type.
- Add update time component methods.
- Add
fromargument tostd.str.string.findmethod. - Rename
std.path.basefunction tostd.path.file_nameand returnstring?. - Rename
std.path.dirfunction tostd.path.parentand returnstring?. - Add
std.fs.read_dirfunction. - Add
std.io.Read.take,std.io.ReadClose.take_closemethods.
Pkg
- Add
parquetmodule.
Tools
- Print warnings in
run/compilecommands.
v0.11.0
Language
Now we published release for Windows platform.
Improved the Closure syntax to support write in one line.
rslet s: string? = "hello"; // Before s.map(|x| { return `${x} world`; }); // After s.map(|x| `${x} world`);spawn,defernow support without block.rsspawn println("hello"); defer println("world");- And with this support, we have to changed empty map initialization from
{}to{:}.
- And with this support, we have to changed empty map initialization from
Add
#[track_caller]annotation for function, see also: Track Callerrs##[track_caller] fn assert_success(value: bool) { assert value == true; } test "assert_success" { assert_success(true); assert_success(false); }Will output:
error: thread 'thread 1#' at 'assertion failed: value == true', test.nv:8 stack backtrace: 0: test#0() at test.nv:8Improve init array with rest expr:
rslet a = [1, 2, 3]; let b = [..a, 4, 5];Add to support unescape in
char.rslet c = '\n';
Stdlib
- Add
std.net.tcpmodule, and here is a guides: Echo Server - Add
std.fs.copy. - Add
std.io.BufReader,std.io.BufWriter. - Add
flushmethod tostd.io.Writeinterface. - Add
std.str.Debugto create debug string with Debug interface.rsstruct MyType {} impl Debug for MyType { fn inspect(self): string { return "MyType"; } } let my_type = MyType{}; assert_eq `${my_type:?}`, "MyType"; - Add
std.backtracemodule to get backtrace info. - Add
std.env.join_pathsmethod. - Improve
std.net.http, removedform,multipartargument, letbodysupport more types. - Improve array's
unique,reverse,sort,sort_by,resize,truncate,clearto return it self. - Imporve
std.processto add Command,process.runnow returnsChildinstance. - Imporve
std.fs,std.processinternal handle for better performance. - Improve
std.path.jointo supports arbitrary argument:path.join("a", "b", "c", "d"). - Improve
std.crypto, letupdateandhmacfunction to supportstring | Bytes. - Fix path join to use
pushavoid cratePathobject. - Rename
std.url.URL->std.url.Url.
Pkg
- Done with
longportpackage.
Tools
We have rewrote navi test, navi doc command, and build a new stdlib docs.
https://navi-lang.org/stdlib/std.crypto
Now, there have more details in the docs, and we will keep improving it.
navi docis rewritten with new output format for better to generate docs.Improve
navi testwith parallel test running and we optimized the test result output.test main2.nv 1/1 ok 0ms test main.nv 2/2 ok 0msImprove
navi test --docto show the correct line number in Markdown file.Add Navi info print when run
navi test,navi benchcommand.Navi 0.11.0 (x86_64-apple-darwin, a76be5f7, 2024-06-07 01:12:17 +08:00)Temporary workaround for
apple-darwin-aarch64to print backtrace.
Other changes
- fmt: leave comma in multi-line array_list.
- fmt: if there is no code in a closure, just an empty {}, no line breaks.
- fmt: Fix missed the function attributes.
- lsp: use custom display_value_type only for inlay hint.
- lsp: call display on ValueType in autocomplete.
- lsp: find_navi_toml_pathbuf and all
*.nvthereunder for cache. - lsp: look for immediate parent dir in create_compile_options.
- lsp: find cache's member info to do when cfg debug assertions
- lsp: auto complete global vars of a Module.
- lsp: check the client’s capabilities and returns either a simple code action capability or a detailed set of supported code action kinds.
- lsp: allow retrying in dispatch.
- lsp: skeleton of handle_code_action, handle_code_action_resolve.
- lsp: search cache_stdlib, cache_userlib to generate fix advice.
v0.10.0
Language
- Added
expect,unwrap,unwrap_or,or,or_else, and,and_then,is_nil,map,map_or,ok_or,inspect,flattenmethods to optional value. - Added
type aliasstatement to define a type alias, andtypestatement to define a newtype. - Improved
do/catchto better handle error. - Added to support call method in union type.
- Added support
tagattribute for newtype serde. - Added to support overridden the default imported names in code scope. e.g.:
Error, you can have your ownstruct Errorto override the defaultError.
Stdlib
- Removed
std.io.Buffer, instead with newstd.io.Bytes. - Moved module under
langtostd, and default importstring,channel,Any,Decimal, removedlangmodule. - Improved to default import
printandprintlnmethod fromstd, now we can call it directly withoutuse. - Added to support log format (full, json, pretty, compact).
- Renamed
URLEncodedFormtoUrlEncodedForminstd.net.http. - Added
File.seekandFile.rewindmethod tostd.fs. - Added to support
flagandmodeoptions forfs.openandFile.openmethod. - Added
fs.copy,fs.copy_dir,fs.rename,fs.hard_link,fs.symlink,fs.unlinkmethod. - Improved
assert_throws, the secondary argument support with a closure to write custom assert.
Pkg
- Added
csvpackage to support read and write CSV file.
Navi Stream
- Add
drawfunction.
Tools
- doc: Added more details doc for array methods.
- doc: Added to support navi-doc to generate method docs in
lang.optional,lang.int... - doc: impl Display for Enum, Struct, Interface, and Module.
- doc: show "instance" for nvs object value types.
- fmt: Updated to indent for switch and case with different levels.
- lsp: Added
navi_streamlanguage match support for Zed editor. - lsp: Added to support goto definition for Navi to Navi Stream source.
- lsp: Added to support show hover info for struct fields.
- lsp: Improved find symbol of TypePathNode::Normal.
- lsp: determine
language_idby file extension. - lsp: find ImportedModule in current module file symbols first.
- lsp: fix bug of there being always an error message left (nvs).
- lsp: generate diagnostics for Navi Stream.
- lsp: optimize inlay hint padding and improve hover info for Navi Stream.
v0.9.6
Language
- Improved the
navi runandnavi testcommands for searching thenavi.tomlwithin a subproject.- Added support for finding
navi.tomlto locate the workspace path. - Added the
navi newcommand to create a new project. - Removed the
--all-diroption fromnavi test, as it is no longer necessary.
- Added support for finding
- Improved the
arraytype to include more methods:map,filter,filter_map,concat,sum,max,min,position_max,position_min,max_by,position_max_by,min_by,position_min_by,product,index_by,contains_by,clone. - Improved the
maptype by addingclonemethods. - Updated the
spawnbehavior to execute immediately. - Fixed support to assign
closuretoclosure?. - Fixed a bug where the interface default method's first argument must be
selferror on release. - Improved internal conversion from char to string.
Stdlib
- Added
std.log. - Added
std.io.Writeas Logger output support and added theprefixmethod. - Fixed serialization to support union types.
- Updated the
to_stringmethods of JSON, YAML, and TOML to supportany?and added more tests. - Fixed serialization bugs for some complex cases.
Tools
We have released the Zed extension for Zed with LSP support. Now code formatting, code completion, hover, go-to-definition, find references, rename, and more features are available in Zed.
- Open your Zed and go to
Extensionsto search fornaviand install it. - Currently, only available for Zed Preview version.
- Open your Zed and go to
doc: Added support to generate
enum,interface,typefor thenavi doccommand.doc: Fixed
implenumnavi docgeneration and included the source code signature by usingnavi-fmtcode generation.lsp: Fixed LSP absolute path in Zed and other compatibility fixes for Zed.
lsp: Enhanced LSP to support showing hover info on expr nodes.
lsp: Fixed LSP inlay hints left padding.
fmt: Fixed to ensure that the semicolon comes before for long lines.
Breaking Changes
- Removed the
--all-diroption fromnavi test, as it is no longer needed. - Renamed
errorinterface toError. - Removed
execute_manyfrom thesqlpackage because it was deprecated in sqlx.
v0.9.5
Core
- Add
decimalas builtin type. - Fix object pool memory leak.
Stdlib
- Improve stdlib throws errors, now all errors has it's own error type.
- Add
std.time.Instant. - Fix std.time.DateTime,
iso8601to use ISO 8601 format,to_stringto use RFC 3339 format. - Add
std.time.Durationandstd.time.DateTime,decimalto support serialize and deserialize. - Fix operator (
>,>=,<,<=) support forstd.time.Duration. - Fix
regex.Capturesgc mark leak.
Pkg
- Add
acquire_timeoutoption forsql.Connection.connect, default is 30s. - Add
extra-enginesupport to sql.Extra Engine backend is a experimental feature, it can be used to execute sql with different engine (CSV, Aliyun OSS, AWS S3, MySQL, PostgreSQL, etc).
- Add
closemethod tosql.Rowsto close the rows. - Add
longportSDK basic feature to support LongPort OpenAPI.
Tools
- Improve Navi LSP performance, and improve auto-completion details.
- Improve zed-navi syntax highlight v0.0.4
- Improve vscode-navi to support decimal.
v0.9.4
Language
Add to support arbitrary parameters.
rs,no_runfn foo(a: int, b: int, items: ..string) { }Add top support iterate for channel types.
rs,no_runuse std.io; let ch = channel::<int>(); spawn { defer { ch.close(); } for i in 0..10 { ch.send(i); } } for n in ch { io.println(n); }Add to support
impl for.rsinterface Foo { fn foo(self); } struct User {} impl for User { fn foo(self) { io.println("foo"); } }Add support lazy initialization.
rslet s: string; s = "hello";Add
chartype.rslet c: char = 'a';Add to support
while let.rswhile (let v = ch.recv()) { io.println(v); }Now can iterate over a string.
rslet s = "hello"; for c in s { io.println(c); }Improve string performance.
Improve string interpolation for support
${x:?}to print debug format.Improve implicit conversion to support.
rs// Option type let a: int? = 10; assert_eq a!, 10; let a: int??? = 10; let b: int? = a; assert_eq b!, 10; let a: int? = 10; let b: int??? = a; assert_eq b!!!, 10; // Union type let a: int | string = "abc"; assert_eq a.(string), "abc"; // Interface let a: ToString = 10; assert_eq a.to_string(), "10";Fix the
breakindo, catchblock can't break the outsideloopbug.
Stdlib
Add
time.sleepmethod.rsuse std.time; // sleep 1 second time.sleep(1);Improve
std.io.printto support arbitrary argument.rsuse std.io; io.println("hello", "world");Update http Headers
apppend,setmethod, not allows nil value.Update http
set_basic_auththeusernamenot allows nil.
Pkg
The pkg is used to manage packages that many split out of Navi in the future.
Add sql module to support SQlite, MySQL, PostgreSQL, etc.
rsuse sql.Connection; struct User { id: int, name: string, } const conn = try! Connection.connect("sqlite::memory:"); try! conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)"); try! conn.execute("INSERT INTO users (name) VALUES (?)", "Jason Lee"); let users = try! conn.query("SELECT * FROM users").scan::<User>();Add markdown module to support markdown render to HTML.
rsuse markdown; let html = markdown.to_html("# Hello, World!");
Tools
- Fix Navi LSP to better autocomplete and documentations support.
- Add cache support in Navi LSP for better performance.
- Add
formatsupport in Navi LSP. - fmt: insert a new line after std uses.
- fmt: sort outer-layer use { ... } statements
- New tree-sitter-navi, tree-sitter-navi-stream project for tree-sitter support.
- Add Zed extension support, current only syntax highlight support.
v0.9.3
Language
Add generic function supports.
Add the
enumsyntax.rsenum Color { Red, Green, Blue, } enum StatusCode { Ok = 200, BadRequest = 400, NotFound = 404, }Add the
constsyntax to define a constant.rsconst PI = 3.1415926;Add the
pubkeyword to define a publicfn,struct,structfield,const,enum..., now only thepubmembers can be visited from other modules.rspub const PI = 3.1415926; pub fn add(a: int, b: int): int { return a + b; } pub struct Loc { pub line: int, pub col: int, }Improve compile error message, and write test case for it.
Allows to visit the
constfrom other modules.Add
r\`raw string\`syntax to better write Regex rules.rsuse std.regex.Regex; // Before let re = Regex.new("\\d+"); // After let re = Regex.new(r`\d+`);Improvement performance for internal calls, string, Object Ref.
Add to support use
_in a number literal.rslet n = 1_234_567.89_012;Add interface inheritance support, and support default implementation.
rsinterface A { fn a(): int; } interface B: A { fn b(): int { return 2; } }Improve assignment detect, now array, map can avoid declaring types, if the left side is a known type.
rsfn foo(items: [string]) {} fn bar(items: <string, int>) {} // Before foo([string] { "a", "b" }); bar(<string, int> { "a": 1, "b": 2 }); // After foo({ "a", "b" }); bar({ "a": 1, "b": 2 });Improve Struct Field and Kw Arguments assignment, if the variable name is the same as the field name, we can use a short syntax.
rsstruct User { name: string, city: string, } impl User { fn new(name: string = "", city: string = ""): User { return User { name: name, city: city, } } } let name = "foo"; let city = "bar"; // Before let user = User { name: name, city: city }; let user = User.new(name: name, city: city); // After let user = User { name, city }; let user = User.new(name:, city:);Add Union Type support.
rsfn foo(n: int | string) { switch (let n = n.(type)) { case int { println("int: {}", n); } case string { println("string: {}", n); } } } // Also can return a union type fn bar(): int | string { return 1; }
Stdlib
Rewrite stdlib by Navi wrapper (internal is Rust Native), for better interface, and error support.
Add
std.io.{Read, Write, Close}interface.Rewrite stdlib by using interface
io.Read,io.Writeinstead of[byte]for support stream, mostly forstd.fsandstd.net.http.rsuse std.net.http; use std.fs; let res = try http.get("https://navi-lang.org"); // Before body is a `[byte]` let body = res.body(); // After // Body is a std.io.Read interface /// https://navi-lang.org/stdlib/std.net.http#Response.body let body = res.body.read_to_string();Add
std.net.http.Clientto create an HTTP client.Add
std.io.Cursorfor writing a[byte]orstringto supportstd.io.Readinterface.Add
json.from_readerto support parse JSON from astd.io.Readin stream.Fix
sortarray incorrect order bug in some cases.Add
std.xmlmodule to support parsing XML.Add
std.tomlmodule to support parsing TOML.Add
std.io.StringBufferfor mutable string likestd.io.Buffer.
Tools
- lsp: Add Go to define support for LSP, and support to visit Navi stdlib source code.
- lsp: Add Hover document for LSP.
- lsp: Add support newline to keep
///comment in next line. - lsp: Add support a bit of Auto Complete support, still need to improve.
- fmt:
usestatement will be sorted by alphabet, and keepselfin the first. - test: Add
navi test --all-dirsto test all sub-dir, and default test current dir. - test: Improve
assertresults and use""to wrap them for a better read. - build: We use Navi to write our internal CI build and publish script now.
v0.9.1
Language
Add to support error handling, see Error doc.
rsfn main() throws { let file = try fs.open("file.txt"); // ... }Add Static Method support, and rewrite all stdlib.
rsstruct User {} impl User { fn new() -> User { // ... } }The first argument on the Instance Method now must have a
selfparameter.rsstruct User {} impl User { // Before fn to_string() { // ... } // After fn to_string(self) { // ... } }Add new serialization support for
json,yamlmodule.rsuse std.json; struct User { name: string ##[serde(rename = "_age")] age: int } let user = json.parse::<User>(`{"name":"Navi","_age":1}`); assert_eq user.name, "Navi"; let user = User { name: "Navi", age: 1 }; assert_eq json.to_string(user), `{"name":"Navi","_age":1}`;- Add also support to deserialize to the
anytype.
rslet a = json.parse::<any>("1"); assert_eq a.(int), 1; let a = json.parse::<any>(`"hello"`); assert_eq a.(string), "hello";- Add also support to deserialize to the
Add Raw String syntax:
r`this is string`for better use for the regular expression.rsuse std.regex.{Regex}; // Before let re = Regex.new("[\\w\\d]"); // After let re = Regex.new(r`[\w\d]`);Improve the
usesyntax to supportasand import multiple items.rs// Before use std.fs; use std.fs.File; // After use std.fs.{self, File as BaseFile, write};Add
typekeyword to define Type Alias.rstype Key = string; type Value = int; type MyInfo = <Key, Value>; let info: MyInfo = { "foo": 1, "bar": 2, };Improve syntax to assign an array, or map without type annotation, if the left side has a known type.
rslet a: [int] = {1, 2, 3}; let b: <string, int> = { "foo": 1, "bar": 2 }; struct Info { headers: <string, string> } let info: Info = { headers: { "Content-Type": "application/json" } };
Stdlib
- Rewrite all stdlib to use Static Method, Error Handling, and the new Serialization support.
- Removed
to_json,to_yamlmethod, usejson.to_string,yaml.to_stirnginstead. - Add
File.open,File.createandfs.write,fs.write_string. - Add
replace_with,replace_all_with,capturestoregex.Regex. - Rename
match,match_alltofindandfind_allforregex.Regexto avoid keywords. - Add
utc,to_offsetmethod totime.DateTime. - Add
stepmethod toRangetype. - Add
bytesmethod to Buffer. - Add
set_filemethod tomultipart.Formto support file upload, see Multipart doc. - Rename
to_int,to_floatintoparse_int,parse_floatfor string.
Tools
- Publish Navi Learn, Navi Stdlib docs on the website.
- And now use Navi instead of TypeScript to write scripts for website docs generated.
- All stdlib docs have been generated by
navi doc --stdlibcommand. - Add Navi Stream doc.
- Add Outline display support for LSP and VS Code extension.
- Add Inlay Hints support for LSP and VS Code extension.
- Add new syntax support for
navi fmt. - Add
navi doccommand to generate documentation for Navi files. - Add
navi doc --stdlibcommand to generate documentation for Navi's standard library. - Add
navi test --doccommand to test the Markdown code blocks in Navi files.
v0.9.0
Language
- Add
interfacesupport. - Add
navi fmtto format code, and install the VS Code extension. - Add
loopstatement to loop forever. - Add getter, and setter to built-in type.
- Add dotenv support, now will auto load
.envfile in the current directory as environment variables. - Add
if letstatement. - Add
mainfunction, nownavi runwill run themainfunction inmain.nvfile in default. - Add httpbin feature into
testharnessto speedup HTTP test.
Stdlib
- Add
resize,truncate,split_off,chunksmethod to array. - Add
weekdaytostd.time. - Add
std.processwithexit,abort,pid,exec,run,argsfunction. - Add
std.json,std.yaml,std.querystringmodules for JSON, YAML, QueryString parse, and stringify. - Add
std.valuemodule to common value type. - Add
basic_authmethod to HTTPRequest. - Add
chunkmethod to HTTPResponse. - Add
multipart,form,timeouttohttp.Request. - Add
read,read_stringtofs.File, andread,read_stringtofsmodule. - Add
std.io.stdin,std.io.stdout,std.io.stderr. - Add
jointostd.url. - Add
std.env.varsto get all vars.
Breaking Changes
- Rewrite string interpolation from
{1 + 2}to${1 + 2}like JavaScript. - Kw Arguments now use
:instead of=, e.g.:fn(a: 1, b: 2), no longer allowed to be passed positionally. - Most struct get method in stdlib now is getter, e.g.:
hostinstead ofhost()forurl.URL. - Rename
fs.read_stringtofs.read_to_string. - Rename
io.from_bytestoio.new_bytes_from_array. - Move
cwd,chdirfromstd.pathtostd.env.
Examples
Interface
Like Go, you can define an interface in the following way:
interface Readable {
fn read(): string
}
fn read(r: Readable): string {
return r.read()
}
struct File {
path: string
}
impl File {
fn read(): string {
return "read file"
}
}
struct Body {
content: string
}
impl Body {
fn read(): string {
return "read body"
}
}
fn main() {
file := File{path: "file"}
body := Body{content: "body"}
println(read(file))
println(read(body))
}If let
use std.io;
fn main() {
let name: string? = "Navi";
if let name = name {
io.println("name is ${name}")
} else {
io.println("name is nil");
}
}